reqwest

Struct ClientBuilder

Source
pub struct ClientBuilder { /* private fields */ }
Expand description

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

Implementations§

Source§

impl ClientBuilder

Source

pub fn new() -> ClientBuilder

Constructs a new ClientBuilder.

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

Source

pub fn build(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.

Source

pub fn user_agent<V>(self, value: V) -> ClientBuilder

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

§Example
// 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?;
Source

pub fn default_headers(self, headers: HeaderMap) -> ClientBuilder

Sets the default headers for every request.

§Example
use reqwest::header;
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?;
Source

pub fn gzip(self, enable: bool) -> ClientBuilder

Enable auto gzip decompression by checking the Content-Encoding response header.

If auto gzip decompression is turned on:

  • When sending a request and if the request’s headers do not already contain an Accept-Encoding and Range values, the Accept-Encoding header is set to gzip. The request body is not automatically compressed.
  • When receiving a response, if its headers contain a Content-Encoding value of gzip, both Content-Encoding and Content-Length are removed from the headers’ set. The response body is automatically decompressed.

If the gzip feature is turned on, the default option is enabled.

§Optional

This requires the optional gzip feature to be enabled

Source

pub fn no_gzip(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.

Source

pub fn no_brotli(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.

Source

pub fn no_zstd(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.

Source

pub fn no_deflate(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.

Source

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

Set a RedirectPolicy for this client.

Default will follow redirects up to a maximum of 10.

Source

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

Enable or disable automatic setting of the Referer header.

Default is true.

Source

pub fn proxy(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.

Source

pub fn no_proxy(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.

Source

pub fn timeout(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.

Source

pub fn read_timeout(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.

Source

pub fn connect_timeout(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.

Source

pub fn connection_verbose(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.

Source

pub fn pool_idle_timeout<D>(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.

Source

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

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

Source

pub fn http1_title_case_headers(self) -> ClientBuilder

Send headers as title case instead of lowercase.

Source

pub fn http1_allow_obsolete_multiline_headers_in_responses( 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.

Source

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

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

Source

pub fn http1_allow_spaces_after_header_name_in_responses( 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.

Source

pub fn http1_only(self) -> ClientBuilder

Only use HTTP/1.

Source

pub fn http09_responses(self) -> ClientBuilder

Allow HTTP/0.9 responses

Source

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

Set whether sockets have TCP_NODELAY enabled.

Default is true.

Source

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

Bind to a local IP Address.

§Example
use std::net::IpAddr;
let local_addr = IpAddr::from([12, 4, 1, 8]);
let client = reqwest::Client::builder()
    .local_address(local_addr)
    .build().unwrap();
Source

pub fn interface(self, interface: &str) -> ClientBuilder

Bind to an interface by SO_BINDTODEVICE.

§Example
let interface = "lo";
let client = reqwest::Client::builder()
    .interface(interface)
    .build().unwrap();
Source

pub fn tcp_keepalive<D>(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.

Source

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

Add a custom root certificate.

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

§Optional

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

Source

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

Add a certificate revocation list.

§Optional

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

Source

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

Add multiple certificate revocation lists.

§Optional

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

Source

pub fn tls_built_in_root_certs( self, tls_built_in_root_certs: bool, ) -> ClientBuilder

Controls the use of built-in/preloaded certificates during certificate validation.

Defaults to true – built-in system certs will be used.

§Bulk Option

If this value is true, all enabled system certs configured with Cargo features will be loaded.

You can set this to false, and enable only a specific source with individual methods. Do that will prevent other sources from being loaded even if their feature Cargo feature is enabled.

§Optional

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

Source

pub fn tls_built_in_webpki_certs(self, enabled: bool) -> ClientBuilder

Sets whether to load webpki root certs with rustls.

If the feature is enabled, this value is true by default.

Source

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

Sets the identity to be used for client certificate authentication.

§Optional

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

Source

pub fn danger_accept_invalid_hostnames( 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.

§Optional

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

Source

pub fn danger_accept_invalid_certs( 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-tls(-...) feature to be enabled.

Source

pub fn tls_sni(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-tls(-...) feature to be enabled.

Source

pub fn min_tls_version(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/default-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-tls(-...) feature to be enabled.

Source

pub fn max_tls_version(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/default-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-tls backend.

§Optional

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

Source

pub fn use_rustls_tls(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-tls(-...) feature to be enabled.

Source

pub fn use_preconfigured_tls(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

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-tls(-...) to be enabled.

Source

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

Add TLS information as TlsInfo extension to responses.

§Optional

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

Source

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

Restrict the Client to be used with HTTPS only requests.

Defaults to false.

Source

pub fn no_hickory_dns(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.

Source

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

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

Warning

Since the DNS protocol has no notion of ports, if you wish to send traffic to a particular port you must include this port in the URL itself, any port in the overridden addr will be ignored and traffic sent to the conventional port for the given scheme (e.g. 80 for http).

Source

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

Override DNS resolution for specific domains to particular IP addresses.

Warning

Since the DNS protocol has no notion of ports, if you wish to send traffic to a particular port you must include this port in the URL itself, any port in the overridden addresses will be ignored and traffic sent to the conventional port for the given scheme (e.g. 80 for http).

Source

pub fn dns_resolver<R: Resolve + 'static>( self, resolver: Arc<R>, ) -> ClientBuilder

Override the DNS resolver implementation.

Pass an Arc wrapping a trait object implementing Resolve. Overrides for specific names passed to resolve and resolve_to_addrs will still be applied on top of this resolver.

Trait Implementations§

Source§

impl Debug for ClientBuilder

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for ClientBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. 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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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>,

Source§

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>,

Source§

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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T