How can I set a timeout for a request in Reqwest?

In Reqwest, which is a popular HTTP client for Rust, you can set a timeout for a request by using the timeout method available on the RequestBuilder. This method allows you to specify a duration after which if the request has not been completed, it will be cancelled with a timeout error.

Here's an example of how to set a timeout for a request in Reqwest:

use reqwest::Client;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = Client::new();

    // Specify your desired timeout duration
    let timeout_duration = Duration::from_secs(10);

    let response = client.get("http://example.com")
        .timeout(timeout_duration)
        .send()
        .await;

    match response {
        Ok(res) => println!("Request was successful: {:?}", res),
        Err(err) => {
            if err.is_timeout() {
                println!("Request timed out");
            } else {
                println!("Request failed: {:?}", err);
            }
        }
    }

    Ok(())
}

In the above example, a GET request is being made to http://example.com with a timeout of 10 seconds. If the server does not respond within 10 seconds, the request will fail with a timeout error, which you can check using err.is_timeout().

It's important to note that the timeout applies to the entire process of the request, not just the connection phase. This includes the time to establish a connection, send the request, and read the response headers and body.

Reqwest also allows setting separate timeouts for the connect phase and for the request phase. Here's how you can set these individual timeouts:

use reqwest::ClientBuilder;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let client = ClientBuilder::new()
        .connect_timeout(Duration::from_secs(5))
        .timeout(Duration::from_secs(30))
        .build()?;

    let response = client.get("http://example.com")
        .send()
        .await;

    // Handle the response as shown in the previous example

    Ok(())
}

In this case, the connect_timeout sets a timeout for the connection phase specifically, and the timeout method on the ClientBuilder sets a timeout for the entire request process, as before.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon