Struct ureq::AgentBuilder

source ·
pub struct AgentBuilder { /* private fields */ }
Expand description

Accumulates options towards building an Agent.

Implementations§

Create a new agent.

Set the proxy server to use for all connections from this Agent.

Example:

let proxy = ureq::Proxy::new("user:password@cool.proxy:9090")?;
let agent = ureq::AgentBuilder::new()
    .proxy(proxy)
    .build();

Enforce the client to only perform HTTPS requests. This setting also makes the client refuse HTTPS to HTTP redirects. Default is false

Example:

let agent = ureq::AgentBuilder::new()
    .https_only(true)
    .build();

Sets the maximum number of connections allowed in the connection pool. By default, this is set to 100. Setting this to zero would disable connection pooling.

let agent = ureq::AgentBuilder::new()
    .max_idle_connections(200)
    .build();

Sets the maximum number of connections per host to keep in the connection pool. By default, this is set to 1. Setting this to zero would disable connection pooling.

let agent = ureq::AgentBuilder::new()
    .max_idle_connections_per_host(200)
    .build();

Configures a custom resolver to be used by this agent. By default, address-resolution is done by std::net::ToSocketAddrs. This allows you to override that resolution with your own alternative. Useful for testing and special-cases like DNS-based load balancing.

A Fn(&str) -> io::Result<Vec<SocketAddr>> is a valid resolver, passing a closure is a simple way to override. Note that you might need explicit type &str on the closure argument for type inference to succeed.

use std::net::ToSocketAddrs;

let mut agent = ureq::AgentBuilder::new()
   .resolver(|addr: &str| match addr {
      "example.com" => Ok(vec![([127,0,0,1], 8096).into()]),
      addr => addr.to_socket_addrs().map(Iterator::collect),
   })
   .build();

Timeout for the socket connection to be successful. If both this and .timeout() are both set, .timeout_connect() takes precedence.

The default is 30 seconds.

use std::time::Duration;
let agent = ureq::builder()
    .timeout_connect(Duration::from_secs(1))
    .build();
let result = agent.get("http://httpbin.org/delay/20").call();

Timeout for the individual reads of the socket. If both this and .timeout() are both set, .timeout() takes precedence.

The default is no timeout. In other words, requests may block forever on reads by default.

use std::time::Duration;
let agent = ureq::builder()
    .timeout_read(Duration::from_secs(1))
    .build();
let result = agent.get("http://httpbin.org/delay/20").call();

Timeout for the individual writes to the socket. If both this and .timeout() are both set, .timeout() takes precedence.

The default is no timeout. In other words, requests may block forever on writes by default.

use std::time::Duration;
let agent = ureq::builder()
    .timeout_read(Duration::from_secs(1))
    .build();
let result = agent.get("http://httpbin.org/delay/20").call();

Timeout for the overall request, including DNS resolution, connection time, redirects, and reading the response body. Slow DNS resolution may cause a request to exceed the timeout, because the DNS request cannot be interrupted with the available APIs.

This takes precedence over .timeout_read() and .timeout_write(), but not .timeout_connect().

// wait max 1 second for whole request to complete.
let agent = ureq::builder()
    .timeout(std::time::Duration::from_secs(1))
    .build();
let result = agent.get("http://httpbin.org/delay/20").call();

Whether no_delay will be set on the tcp socket. Setting this to true disables Nagle’s algorithm.

Defaults to true.

let agent = ureq::builder()
    .no_delay(false)
    .build();
let result = agent.get("http://httpbin.org/get").call();

How many redirects to follow.

Defaults to 5. Set to 0 to avoid redirects and instead get a response object with the 3xx status code.

If the redirect count hits this limit (and it’s > 0), TooManyRedirects is returned.

WARNING: for 307 and 308 redirects, this value is ignored for methods that have a body. You must handle 307 redirects yourself when sending a PUT, POST, PATCH, or DELETE request.

let result = ureq::builder()
    .redirects(1)
    .build()
    .get("http://httpbin.org/status/301")
    .call()?;
assert_ne!(result.status(), 301);

let result = ureq::post("http://httpbin.org/status/307")
    .send_bytes(b"some data")?;
assert_eq!(result.status(), 307);

Set the strategy for propagation of authorization headers in redirects.

Defaults to RedirectAuthHeaders::Never.

The user-agent header to associate with all requests from this agent by default.

Defaults to ureq/[VERSION]. You can override the user-agent on an individual request by setting the User-Agent header when constructing the request.

let agent = ureq::builder()
    .user_agent("ferris/1.0")
    .build();

// Uses agent's header
let result: serde_json::Value =
    agent.get("http://httpbin.org/headers").call()?.into_json()?;
assert_eq!(&result["headers"]["User-Agent"], "ferris/1.0");

// Overrides user-agent set on the agent
let result: serde_json::Value = agent.get("http://httpbin.org/headers")
    .set("User-Agent", "super-ferris/2.0")
    .call()?.into_json()?;
assert_eq!(&result["headers"]["User-Agent"], "super-ferris/2.0");

Configure TLS options for rustls to use when making HTTPS connections from this Agent.

This overrides any previous call to tls_config or tls_connector.

use std::sync::Arc;
let mut root_store = rustls::RootCertStore::empty();
root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| {
    rustls::OwnedTrustAnchor::from_subject_spki_name_constraints(
        ta.subject,
        ta.spki,
        ta.name_constraints,
    )
}));

let tls_config = rustls::ClientConfig::builder()
    .with_safe_defaults()
    .with_root_certificates(root_store)
    .with_no_client_auth();
let agent = ureq::builder()
    .tls_config(Arc::new(tls_config))
    .build();

Configure TLS options for a backend other than rustls. The parameter can be a any type which implements the TlsConnector trait. If you enable the native-tls feature, we provide impl TlsConnector for native_tls::TlsConnector so you can pass Arc<native_tls::TlsConnector>.

This overrides any previous call to tls_config or tls_connector.

use std::sync::Arc;
let tls_connector = Arc::new(native_tls::TlsConnector::new()?);
let agent = ureq::builder()
    .tls_connector(tls_connector.clone())
    .build();

Provide the cookie store to be used for all requests using this agent.

This is useful in two cases. First when there is a need to persist cookies to some backing store, and second when there’s a need to prepare the agent with some pre-existing cookies.

Example

use cookie_store::CookieStore;
use std::fs::File;
use std::io::BufReader;
let file = File::open("cookies.json")?;
let read = BufReader::new(file);

// Read persisted cookies from cookies.json
let my_store = CookieStore::load_json(read).unwrap();

// Cookies will be used for requests done through agent.
let agent = ureq::builder()
    .cookie_store(my_store)
    .build();

Add middleware handler to this agent.

All requests made by the agent will use this middleware. Middleware is invoked in the order they are added to the builder.

Trait Implementations§

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.