pub struct AgentBuilder { /* private fields */ }
Expand description
Accumulates options towards building an Agent.
Implementations§
Source§impl AgentBuilder
impl AgentBuilder
pub fn new() -> Self
Sourcepub fn proxy(self, proxy: Proxy) -> Self
pub fn proxy(self, proxy: Proxy) -> Self
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();
Adding a proxy will disable try_proxy_from_env
.
Sourcepub fn try_proxy_from_env(self, do_try: bool) -> Self
pub fn try_proxy_from_env(self, do_try: bool) -> Self
Attempt to detect proxy settings from the environment, i.e. HTTP_PROXY
The default is false
without the proxy-from-env
feature flag, i.e.
not detecting proxy from env, due to the potential security risk and to
maintain backward compatibility.
If the proxy
is set on the builder, this setting has no effect.
Sourcepub fn https_only(self, enforce: bool) -> Self
pub fn https_only(self, enforce: bool) -> Self
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();
Sourcepub fn max_idle_connections(self, max: usize) -> Self
pub fn max_idle_connections(self, max: usize) -> Self
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();
Sourcepub fn max_idle_connections_per_host(self, max: usize) -> Self
pub fn max_idle_connections_per_host(self, max: usize) -> Self
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();
Sourcepub fn resolver(self, resolver: impl Resolver + 'static) -> Self
pub fn resolver(self, resolver: impl Resolver + 'static) -> Self
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();
Sourcepub fn timeout_connect(self, timeout: Duration) -> Self
pub fn timeout_connect(self, timeout: Duration) -> Self
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();
Sourcepub fn timeout_read(self, timeout: Duration) -> Self
pub fn timeout_read(self, timeout: Duration) -> Self
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();
Sourcepub fn timeout_write(self, timeout: Duration) -> Self
pub fn timeout_write(self, timeout: Duration) -> Self
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();
Sourcepub fn timeout(self, timeout: Duration) -> Self
pub fn timeout(self, timeout: Duration) -> Self
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();
Sourcepub fn no_delay(self, no_delay: bool) -> Self
pub fn no_delay(self, no_delay: bool) -> Self
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();
Sourcepub fn redirects(self, n: u32) -> Self
pub fn redirects(self, n: u32) -> Self
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);
Sourcepub fn redirect_auth_headers(self, v: RedirectAuthHeaders) -> Self
pub fn redirect_auth_headers(self, v: RedirectAuthHeaders) -> Self
Set the strategy for propagation of authorization headers in redirects.
Defaults to RedirectAuthHeaders::Never
.
Sourcepub fn user_agent(self, user_agent: &str) -> Self
pub fn user_agent(self, user_agent: &str) -> Self
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");
Sourcepub fn tls_config(self, tls_config: Arc<ClientConfig>) -> Self
Available on crate feature tls
only.
pub fn tls_config(self, tls_config: Arc<ClientConfig>) -> Self
tls
only.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 {
roots: webpki_roots::TLS_SERVER_ROOTS.iter().cloned().collect(),
};
let tls_config = rustls::ClientConfig::builder()
.with_root_certificates(root_store)
.with_no_client_auth();
let agent = ureq::builder()
.tls_config(Arc::new(tls_config))
.build();
Sourcepub fn tls_connector<T: TlsConnector + 'static>(
self,
tls_config: Arc<T>,
) -> Self
pub fn tls_connector<T: TlsConnector + 'static>( self, tls_config: Arc<T>, ) -> Self
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();
Available on crate feature cookies
only.
cookies
only.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();
Sourcepub fn middleware(self, m: impl Middleware) -> Self
pub fn middleware(self, m: impl Middleware) -> Self
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.