Struct ureq::AgentBuilder

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

Accumulates options towards building an Agent.

Implementations§

source§

impl AgentBuilder

source

pub fn new() -> Self

source

pub fn build(self) -> Agent

Create a new agent.

source

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.

source

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.

source

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();
source

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();
source

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();
source

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();
source

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();
source

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();
source

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();
source

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();
source

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();
source

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);
source

pub fn redirect_auth_headers(self, v: RedirectAuthHeaders) -> Self

Set the strategy for propagation of authorization headers in redirects.

Defaults to RedirectAuthHeaders::Never.

source

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");
source

pub fn tls_config(self, tls_config: Arc<ClientConfig>) -> Self

Available on crate feature 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();
source

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();
source

pub fn cookie_store(self, cookie_store: CookieStore) -> Self

Available on crate feature 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();
source

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.

Trait Implementations§

source§

impl Debug for AgentBuilder

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

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

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.