Struct ClientBuilder

struct ClientBuilder { ... }

A ClientBuilder can be used to create a Client with custom configuration.

Implementations

impl ClientBuilder

fn build(self: Self) -> Result<Client>

Returns a Client that uses this ClientBuilder configuration.

Errors

This method fails if a TLS backend cannot be initialized, or the resolver cannot load the system configuration.

fn user_agent<V>(self: Self, value: V) -> ClientBuilder
where
    V: TryInto<HeaderValue>,
    <V as >::Error: Into<Error>

Sets the User-Agent header to be used by this client.

Example

# async fn doc() -> Result<(), reqwest::Error> {
// Name your user agent after your app?
static APP_USER_AGENT: &str = concat!(
    env!("CARGO_PKG_NAME"),
    "/",
    env!("CARGO_PKG_VERSION"),
);

let client = reqwest::Client::builder()
    .user_agent(APP_USER_AGENT)
    .build()?;
let res = client.get("https://www.rust-lang.org").send().await?;
# Ok(())
# }
fn default_headers(self: Self, headers: HeaderMap) -> ClientBuilder

Sets the default headers for every request.

Example

use reqwest::header;
# async fn doc() -> Result<(), reqwest::Error> {
let mut headers = header::HeaderMap::new();
headers.insert("X-MY-HEADER", header::HeaderValue::from_static("value"));

// Consider marking security-sensitive headers with `set_sensitive`.
let mut auth_value = header::HeaderValue::from_static("secret");
auth_value.set_sensitive(true);
headers.insert(header::AUTHORIZATION, auth_value);

// get a client builder
let client = reqwest::Client::builder()
    .default_headers(headers)
    .build()?;
let res = client.get("https://www.rust-lang.org").send().await?;
# Ok(())
# }
fn no_gzip(self: Self) -> ClientBuilder

Disable auto response body gzip decompression.

This method exists even if the optional gzip feature is not enabled. This can be used to ensure a Client doesn't use gzip decompression even if another dependency were to enable the optional gzip feature.

fn no_brotli(self: Self) -> ClientBuilder

Disable auto response body brotli decompression.

This method exists even if the optional brotli feature is not enabled. This can be used to ensure a Client doesn't use brotli decompression even if another dependency were to enable the optional brotli feature.

fn no_zstd(self: Self) -> ClientBuilder

Disable auto response body zstd decompression.

This method exists even if the optional zstd feature is not enabled. This can be used to ensure a Client doesn't use zstd decompression even if another dependency were to enable the optional zstd feature.

fn no_deflate(self: Self) -> ClientBuilder

Disable auto response body deflate decompression.

This method exists even if the optional deflate feature is not enabled. This can be used to ensure a Client doesn't use deflate decompression even if another dependency were to enable the optional deflate feature.

fn redirect(self: Self, policy: Policy) -> ClientBuilder

Set a RedirectPolicy for this client.

Default will follow redirects up to a maximum of 10.

fn referer(self: Self, enable: bool) -> ClientBuilder

Enable or disable automatic setting of the Referer header.

Default is true.

fn retry(self: Self, policy: Builder) -> ClientBuilder

Set a request retry policy.

Default behavior is to retry protocol NACKs.

fn proxy(self: Self, proxy: Proxy) -> ClientBuilder

Add a Proxy to the list of proxies the Client will use.

Note

Adding a proxy will disable the automatic usage of the "system" proxy.

fn no_proxy(self: Self) -> ClientBuilder

Clear all Proxies, so Client will use no proxy anymore.

Note

To add a proxy exclusion list, use [crate::proxy::Proxy::no_proxy()] on all desired proxies instead.

This also disables the automatic usage of the "system" proxy.

fn timeout(self: Self, timeout: Duration) -> ClientBuilder

Enables a total request timeout.

The timeout is applied from when the request starts connecting until the response body has finished. Also considered a total deadline.

Default is no timeout.

fn read_timeout(self: Self, timeout: Duration) -> ClientBuilder

Enables a read timeout.

The timeout applies to each read operation, and resets after a successful read. This is more appropriate for detecting stalled connections when the size isn't known beforehand.

Default is no timeout.

fn connect_timeout(self: Self, timeout: Duration) -> ClientBuilder

Set a timeout for only the connect phase of a Client.

Default is None.

Note

This requires the futures be executed in a tokio runtime with a tokio timer enabled.

fn connection_verbose(self: Self, verbose: bool) -> ClientBuilder

Set whether connections should emit verbose logs.

Enabling this option will emit log messages at the TRACE level for read and write operations on connections.

fn pool_idle_timeout<D>(self: Self, val: D) -> ClientBuilder
where
    D: Into<Option<Duration>>

Set an optional timeout for idle sockets being kept-alive.

Pass None to disable timeout.

Default is 90 seconds.

fn pool_max_idle_per_host(self: Self, max: usize) -> ClientBuilder

Sets the maximum idle connection per host allowed in the pool.

Default is usize::MAX (no limit).

fn http1_title_case_headers(self: Self) -> ClientBuilder

Send headers as title case instead of lowercase.

fn http1_allow_obsolete_multiline_headers_in_responses(self: Self, value: bool) -> ClientBuilder

Set whether HTTP/1 connections will accept obsolete line folding for header values.

Newline codepoints (\r and \n) will be transformed to spaces when parsing.

fn http1_ignore_invalid_headers_in_responses(self: Self, value: bool) -> ClientBuilder

Sets whether invalid header lines should be silently ignored in HTTP/1 responses.

fn http1_allow_spaces_after_header_name_in_responses(self: Self, value: bool) -> ClientBuilder

Set whether HTTP/1 connections will accept spaces between header names and the colon that follow them in responses.

Newline codepoints (\r and \n) will be transformed to spaces when parsing.

fn http1_only(self: Self) -> ClientBuilder

Only use HTTP/1.

fn http09_responses(self: Self) -> ClientBuilder

Allow HTTP/0.9 responses

fn http2_prior_knowledge(self: Self) -> ClientBuilder

Only use HTTP/2.

fn http2_initial_stream_window_size<impl Into<Option<u32>>: Into<Option<u32>>>(self: Self, sz: impl Into<Option<u32>>) -> ClientBuilder

Sets the SETTINGS_INITIAL_WINDOW_SIZE option for HTTP2 stream-level flow control.

Default is currently 65,535 but may change internally to optimize for common uses.

fn http2_initial_connection_window_size<impl Into<Option<u32>>: Into<Option<u32>>>(self: Self, sz: impl Into<Option<u32>>) -> ClientBuilder

Sets the max connection-level flow control for HTTP2

Default is currently 65,535 but may change internally to optimize for common uses.

fn http2_adaptive_window(self: Self, enabled: bool) -> ClientBuilder

Sets whether to use an adaptive flow control.

Enabling this will override the limits set in http2_initial_stream_window_size and http2_initial_connection_window_size.

fn http2_max_frame_size<impl Into<Option<u32>>: Into<Option<u32>>>(self: Self, sz: impl Into<Option<u32>>) -> ClientBuilder

Sets the maximum frame size to use for HTTP2.

Default is currently 16,384 but may change internally to optimize for common uses.

fn http2_max_header_list_size(self: Self, max_header_size_bytes: u32) -> ClientBuilder

Sets the maximum size of received header frames for HTTP2.

Default is currently 16KB, but can change.

fn http2_keep_alive_interval<impl Into<Option<Duration>>: Into<Option<Duration>>>(self: Self, interval: impl Into<Option<Duration>>) -> ClientBuilder

Sets an interval for HTTP2 Ping frames should be sent to keep a connection alive.

Pass None to disable HTTP2 keep-alive. Default is currently disabled.

fn http2_keep_alive_timeout(self: Self, timeout: Duration) -> ClientBuilder

Sets a timeout for receiving an acknowledgement of the keep-alive ping.

If the ping is not acknowledged within the timeout, the connection will be closed. Does nothing if http2_keep_alive_interval is disabled. Default is currently disabled.

fn http2_keep_alive_while_idle(self: Self, enabled: bool) -> ClientBuilder

Sets whether HTTP2 keep-alive should apply while the connection is idle.

If disabled, keep-alive pings are only sent while there are open request/responses streams. If enabled, pings are also sent when no streams are active. Does nothing if http2_keep_alive_interval is disabled. Default is false.

fn tcp_nodelay(self: Self, enabled: bool) -> ClientBuilder

Set whether sockets have TCP_NODELAY enabled.

Default is true.

fn local_address<T>(self: Self, addr: T) -> ClientBuilder
where
    T: Into<Option<IpAddr>>

Bind to a local IP Address.

Example

# fn doc() -> Result<(), reqwest::Error> {
use std::net::IpAddr;
let local_addr = IpAddr::from([12, 4, 1, 8]);
let client = reqwest::Client::builder()
    .local_address(local_addr)
    .build()?;
# Ok(())
# }
fn interface(self: Self, interface: &str) -> ClientBuilder

Bind connections only on the specified network interface.

This option is only available on the following operating systems:

  • Android
  • Fuchsia
  • Linux,
  • macOS and macOS-like systems (iOS, tvOS, watchOS and visionOS)
  • Solaris and illumos

On Android, Linux, and Fuchsia, this uses the SO_BINDTODEVICE socket option. On macOS and macOS-like systems, Solaris, and illumos, this instead uses the IP_BOUND_IF and IPV6_BOUND_IF socket options (as appropriate).

Note that connections will fail if the provided interface name is not a network interface that currently exists when a connection is established.

Example

# fn doc() -> Result<(), reqwest::Error> {
let interface = "lo";
let client = reqwest::Client::builder()
    .interface(interface)
    .build()?;
# Ok(())
# }
fn tcp_keepalive<D>(self: Self, val: D) -> ClientBuilder
where
    D: Into<Option<Duration>>

Set that all sockets have SO_KEEPALIVE set with the supplied duration.

If None, the option will not be set.

fn tcp_keepalive_interval<D>(self: Self, val: D) -> ClientBuilder
where
    D: Into<Option<Duration>>

Set that all sockets have SO_KEEPALIVE set with the supplied interval.

If None, the option will not be set.

fn tcp_keepalive_retries<C>(self: Self, retries: C) -> ClientBuilder
where
    C: Into<Option<u32>>

Set that all sockets have SO_KEEPALIVE set with the supplied retry count.

If None, the option will not be set.

fn tcp_user_timeout<D>(self: Self, val: D) -> ClientBuilder
where
    D: Into<Option<Duration>>

Set that all sockets have TCP_USER_TIMEOUT set with the supplied duration.

This option controls how long transmitted data may remain unacknowledged before the connection is force-closed.

If None, the option will not be set.

fn unix_socket<impl UnixSocketProvider: UnixSocketProvider>(self: Self, path: impl UnixSocketProvider) -> ClientBuilder

Set that all connections will use this Unix socket.

If a request URI uses the https scheme, TLS will still be used over the Unix socket.

Note

This option is not compatible with any of the TCP or Proxy options. Setting this will ignore all those options previously set.

Likewise, DNS resolution will not be done on the domain name.

fn tls_certs_merge<impl IntoIterator<Item = Certificate>: IntoIterator<Item = Certificate>>(self: Self, certs: impl IntoIterator<Item = Certificate>) -> ClientBuilder

Add custom certificate roots.

This can be used to connect to a server that has a self-signed certificate for example.

This optional attempts to merge with any native or built-in roots.

Errors

If the selected TLS backend or verifier does not support merging certificates, the builder will return an error.

Optional

This requires the optional default-tls, native-tls, or rustls(-...) feature to be enabled.

fn tls_certs_only<impl IntoIterator<Item = Certificate>: IntoIterator<Item = Certificate>>(self: Self, certs: impl IntoIterator<Item = Certificate>) -> ClientBuilder

Use only the provided certificate roots.

This can be used to connect to a server that has a self-signed certificate for example.

This option disables any native or built-in roots, and only uses the roots provided to this method.

Optional

This requires the optional default-tls, native-tls, or rustls(-...) feature to be enabled.

fn add_root_certificate(self: Self, cert: Certificate) -> ClientBuilder

Deprecated: use [ClientBuilder::tls_certs_merge()] or [ClientBuilder::tls_certs_only()] instead.

fn tls_crls_only<impl IntoIterator<Item = CertificateRevocationList>: IntoIterator<Item = CertificateRevocationList>>(self: Self, crls: impl IntoIterator<Item = CertificateRevocationList>) -> ClientBuilder

Add multiple certificate revocation lists.

Errors

This only works if also using only provided root certificates. This cannot work with the native verifier.

If CRLs are added but tls_certs_only() is not called, the builder will return an error.

Optional

This requires the rustls(-...) Cargo feature enabled.

fn add_crl(self: Self, crl: CertificateRevocationList) -> ClientBuilder

Deprecated: use [ClientBuilder::tls_crls_only()] instead.

fn add_crls<impl IntoIterator<Item = CertificateRevocationList>: IntoIterator<Item = CertificateRevocationList>>(self: Self, crls: impl IntoIterator<Item = CertificateRevocationList>) -> ClientBuilder

Deprecated: use [ClientBuilder::tls_crls_only()] instead.

fn identity(self: Self, identity: Identity) -> ClientBuilder

Sets the identity to be used for client certificate authentication.

Optional

This requires the optional native-tls or rustls(-...) feature to be enabled.

fn tls_danger_accept_invalid_hostnames(self: Self, accept_invalid_hostname: bool) -> ClientBuilder

Controls the use of hostname verification.

Defaults to false.

Warning

You should think very carefully before you use this method. If hostname verification is not used, any valid certificate for any site will be trusted for use from any other. This introduces a significant vulnerability to man-in-the-middle attacks.

Errors

Depending on the TLS backend and verifier, this might not work with native certificates, only those added with [ClientBuilder::tls_certs_only()].

Optional

This requires the optional default-tls, native-tls, or rustls(-...) feature to be enabled.

fn danger_accept_invalid_hostnames(self: Self, accept_invalid_hostname: bool) -> ClientBuilder

Deprecated: use [ClientBuilder::tls_danger_accept_invalid_hostnames()] instead.

fn tls_danger_accept_invalid_certs(self: Self, accept_invalid_certs: bool) -> ClientBuilder

Controls the use of certificate validation.

Defaults to false.

Warning

You should think very carefully before using this method. If invalid certificates are trusted, any certificate for any site will be trusted for use. This includes expired certificates. This introduces significant vulnerabilities, and should only be used as a last resort.

Optional

This requires the optional default-tls, native-tls, or rustls(-...) feature to be enabled.

fn danger_accept_invalid_certs(self: Self, accept_invalid_certs: bool) -> ClientBuilder

Deprecated: use [ClientBuilder::tls_danger_accept_invalid_certs()] instead.

fn tls_sni(self: Self, tls_sni: bool) -> ClientBuilder

Controls the use of TLS server name indication.

Defaults to true.

Optional

This requires the optional default-tls, native-tls, or rustls(-...) feature to be enabled.

fn tls_version_min(self: Self, version: Version) -> ClientBuilder

Set the minimum required TLS version for connections.

By default, the TLS backend's own default is used.

Errors

A value of tls::Version::TLS_1_3 will cause an error with the native-tls backend. This does not mean the version isn't supported, just that it can't be set as a minimum due to technical limitations.

Optional

This requires the optional default-tls, native-tls, or rustls(-...) feature to be enabled.

fn min_tls_version(self: Self, version: Version) -> ClientBuilder

Deprecated: use [ClientBuilder::tls_version_min()] instead.

fn tls_version_max(self: Self, version: Version) -> ClientBuilder

Set the maximum allowed TLS version for connections.

By default, there's no maximum.

Errors

A value of tls::Version::TLS_1_3 will cause an error with the native-tls backend. This does not mean the version isn't supported, just that it can't be set as a maximum due to technical limitations.

Cannot set a maximum outside the protocol versions supported by rustls with the rustls backend.

Optional

This requires the optional default-tls, native-tls, or rustls(-...) feature to be enabled.

fn max_tls_version(self: Self, version: Version) -> ClientBuilder

Deprecated: use [ClientBuilder::tls_version_max()] instead.

fn tls_backend_rustls(self: Self) -> ClientBuilder

Force using the Rustls TLS backend.

Since multiple TLS backends can be optionally enabled, this option will force the rustls backend to be used for this Client.

Optional

This requires the optional rustls(-...) feature to be enabled.

fn use_rustls_tls(self: Self) -> ClientBuilder

Deprecated: use [ClientBuilder::tls_backend_rustls()] instead.

fn tls_backend_preconfigured<impl Any: Any>(self: Self, tls: impl Any) -> ClientBuilder

Use a preconfigured TLS backend.

If the passed Any argument is not a TLS backend that reqwest understands, the ClientBuilder will error when calling build.

Advanced

There is no semver stability on the internals of this method. Use at your own risk.

This is an advanced option, and can be somewhat brittle. Usage requires keeping the preconfigured TLS argument version in sync with reqwest, since version mismatches will result in an "unknown" TLS backend.

If possible, it's preferable to use the methods on ClientBuilder to configure reqwest's TLS.

Optional

This requires one of the optional features native-tls or rustls(-...) to be enabled.

fn use_preconfigured_tls<impl Any: Any>(self: Self, tls: impl Any) -> ClientBuilder

Deprecated: use [ClientBuilder::tls_backend_preconfigured()] instead.

fn tls_info(self: Self, tls_info: bool) -> ClientBuilder

Add TLS information as TlsInfo extension to responses.

Optional

This requires the optional default-tls, native-tls, or rustls(-...) feature to be enabled.

fn https_only(self: Self, enabled: bool) -> ClientBuilder

Restrict the Client to be used with HTTPS only requests.

Defaults to false.

fn no_hickory_dns(self: Self) -> ClientBuilder

Disables the hickory-dns async resolver.

This method exists even if the optional hickory-dns feature is not enabled. This can be used to ensure a Client doesn't use the hickory-dns async resolver even if another dependency were to enable the optional hickory-dns feature.

fn resolve(self: Self, domain: &str, addr: SocketAddr) -> ClientBuilder

Override DNS resolution for specific domains to a particular IP address.

Set the port to 0 to use the conventional port for the given scheme (e.g. 80 for http). Ports in the URL itself will always be used instead of the port in the overridden addr.

fn resolve_to_addrs(self: Self, domain: &str, addrs: &[SocketAddr]) -> ClientBuilder

Override DNS resolution for specific domains to particular IP addresses.

Set the port to 0 to use the conventional port for the given scheme (e.g. 80 for http). Ports in the URL itself will always be used instead of the port in the overridden addr.

fn dns_resolver<R>(self: Self, resolver: R) -> ClientBuilder
where
    R: IntoResolve

Override the DNS resolver implementation.

Overrides for specific names passed to resolve and resolve_to_addrs will still be applied on top of this resolver.

fn connector_layer<L>(self: Self, layer: L) -> ClientBuilder
where
    L: Layer<BoxCloneSyncService<Unnameable, Conn, Box<dyn StdError + Send + Sync>>> + Clone + Send + Sync + 'static,
    <L as >::Service: Service<Unnameable, Response = Conn, Error = Box<dyn StdError + Send + Sync>> + Clone + Send + Sync + 'static,
    <<L as >::Service as Service<Unnameable>>::Future: Send + 'static

Adds a new Tower Layer to the base connector Service which is responsible for connection establishment.

Each subsequent invocation of this function will wrap previous layers.

If configured, the connect_timeout will be the outermost layer.

Example usage:

use std::time::Duration;

# #[cfg(not(feature = "rustls-no-provider"))]
let client = reqwest::Client::builder()
                     // resolved to outermost layer, meaning while we are waiting on concurrency limit
                     .connect_timeout(Duration::from_millis(200))
                     // underneath the concurrency check, so only after concurrency limit lets us through
                     .connector_layer(tower::timeout::TimeoutLayer::new(Duration::from_millis(50)))
                     .connector_layer(tower::limit::concurrency::ConcurrencyLimitLayer::new(2))
                     .build()
                     .unwrap();

impl ClientBuilder

fn new() -> Self

Constructs a new ClientBuilder.

This is the same as Client::builder().

impl Debug for ClientBuilder

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

impl Default for ClientBuilder

fn default() -> Self

impl Freeze for ClientBuilder

impl RefUnwindSafe for ClientBuilder

impl Send for ClientBuilder

impl Sync for ClientBuilder

impl Unpin for ClientBuilder

impl UnsafeUnpin for ClientBuilder

impl UnwindSafe for ClientBuilder

impl<T> Any for ClientBuilder

fn type_id(self: &Self) -> TypeId

impl<T> Borrow for ClientBuilder

fn borrow(self: &Self) -> &T

impl<T> BorrowMut for ClientBuilder

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

impl<T> ErasedDestructor for ClientBuilder

impl<T> From for ClientBuilder

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> Instrument for ClientBuilder

impl<T> PolicyExt for ClientBuilder

fn and<P, B, E>(self: Self, other: P) -> And<T, P>
where
    T: Policy<B, E>,
    P: Policy<B, E>
fn or<P, B, E>(self: Self, other: P) -> Or<T, P>
where
    T: Policy<B, E>,
    P: Policy<B, E>

impl<T> WithSubscriber for ClientBuilder

impl<T, U> Into for ClientBuilder

fn into(self: Self) -> U

Calls U::from(self).

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

impl<T, U> TryFrom for ClientBuilder

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

impl<T, U> TryInto for ClientBuilder

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