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
Clientthat uses thisClientBuilderconfiguration.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-Agentheader to be used by this client.Example
# asyncfn default_headers(self: Self, headers: HeaderMap) -> ClientBuilderSets the default headers for every request.
Example
use header; # asyncfn no_gzip(self: Self) -> ClientBuilderDisable auto response body gzip decompression.
This method exists even if the optional
gzipfeature is not enabled. This can be used to ensure aClientdoesn't use gzip decompression even if another dependency were to enable the optionalgzipfeature.fn no_brotli(self: Self) -> ClientBuilderDisable auto response body brotli decompression.
This method exists even if the optional
brotlifeature is not enabled. This can be used to ensure aClientdoesn't use brotli decompression even if another dependency were to enable the optionalbrotlifeature.fn no_zstd(self: Self) -> ClientBuilderDisable auto response body zstd decompression.
This method exists even if the optional
zstdfeature is not enabled. This can be used to ensure aClientdoesn't use zstd decompression even if another dependency were to enable the optionalzstdfeature.fn no_deflate(self: Self) -> ClientBuilderDisable auto response body deflate decompression.
This method exists even if the optional
deflatefeature is not enabled. This can be used to ensure aClientdoesn't use deflate decompression even if another dependency were to enable the optionaldeflatefeature.fn redirect(self: Self, policy: Policy) -> ClientBuilderSet a
RedirectPolicyfor this client.Default will follow redirects up to a maximum of 10.
fn referer(self: Self, enable: bool) -> ClientBuilderEnable or disable automatic setting of the
Refererheader.Default is
true.fn retry(self: Self, policy: Builder) -> ClientBuilderSet a request retry policy.
Default behavior is to retry protocol NACKs.
fn proxy(self: Self, proxy: Proxy) -> ClientBuilderAdd a
Proxyto the list of proxies theClientwill use.Note
Adding a proxy will disable the automatic usage of the "system" proxy.
fn no_proxy(self: Self) -> ClientBuilderClear all
Proxies, soClientwill 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) -> ClientBuilderEnables 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) -> ClientBuilderEnables 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) -> ClientBuilderSet 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) -> ClientBuilderSet whether connections should emit verbose logs.
Enabling this option will emit log messages at the
TRACElevel 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
Noneto disable timeout.Default is 90 seconds.
fn pool_max_idle_per_host(self: Self, max: usize) -> ClientBuilderSets the maximum idle connection per host allowed in the pool.
Default is
usize::MAX(no limit).fn http1_title_case_headers(self: Self) -> ClientBuilderSend headers as title case instead of lowercase.
fn http1_allow_obsolete_multiline_headers_in_responses(self: Self, value: bool) -> ClientBuilderSet whether HTTP/1 connections will accept obsolete line folding for header values.
Newline codepoints (
\rand\n) will be transformed to spaces when parsing.fn http1_ignore_invalid_headers_in_responses(self: Self, value: bool) -> ClientBuilderSets 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) -> ClientBuilderSet whether HTTP/1 connections will accept spaces between header names and the colon that follow them in responses.
Newline codepoints (
\rand\n) will be transformed to spaces when parsing.fn http1_only(self: Self) -> ClientBuilderOnly use HTTP/1.
fn http09_responses(self: Self) -> ClientBuilderAllow HTTP/0.9 responses
fn http2_prior_knowledge(self: Self) -> ClientBuilderOnly use HTTP/2.
fn http2_initial_stream_window_size<impl Into<Option<u32>>: Into<Option<u32>>>(self: Self, sz: impl Into<Option<u32>>) -> ClientBuilderSets the
SETTINGS_INITIAL_WINDOW_SIZEoption 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>>) -> ClientBuilderSets 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) -> ClientBuilderSets whether to use an adaptive flow control.
Enabling this will override the limits set in
http2_initial_stream_window_sizeandhttp2_initial_connection_window_size.fn http2_max_frame_size<impl Into<Option<u32>>: Into<Option<u32>>>(self: Self, sz: impl Into<Option<u32>>) -> ClientBuilderSets 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) -> ClientBuilderSets 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>>) -> ClientBuilderSets an interval for HTTP2 Ping frames should be sent to keep a connection alive.
Pass
Noneto disable HTTP2 keep-alive. Default is currently disabled.fn http2_keep_alive_timeout(self: Self, timeout: Duration) -> ClientBuilderSets 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_intervalis disabled. Default is currently disabled.fn http2_keep_alive_while_idle(self: Self, enabled: bool) -> ClientBuilderSets 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_intervalis disabled. Default isfalse.fn tcp_nodelay(self: Self, enabled: bool) -> ClientBuilderSet whether sockets have
TCP_NODELAYenabled.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 interface(self: Self, interface: &str) -> ClientBuilderBind 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_BINDTODEVICEsocket option. On macOS and macOS-like systems, Solaris, and illumos, this instead uses theIP_BOUND_IFandIPV6_BOUND_IFsocket 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 tcp_keepalive<D>(self: Self, val: D) -> ClientBuilder where D: Into<Option<Duration>>Set that all sockets have
SO_KEEPALIVEset 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_KEEPALIVEset 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_KEEPALIVEset 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_TIMEOUTset 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) -> ClientBuilderSet that all connections will use this Unix socket.
If a request URI uses the
httpsscheme, 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>) -> ClientBuilderAdd 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, orrustls(-...)feature to be enabled.fn tls_certs_only<impl IntoIterator<Item = Certificate>: IntoIterator<Item = Certificate>>(self: Self, certs: impl IntoIterator<Item = Certificate>) -> ClientBuilderUse 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, orrustls(-...)feature to be enabled.fn add_root_certificate(self: Self, cert: Certificate) -> ClientBuilderDeprecated: 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>) -> ClientBuilderAdd 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) -> ClientBuilderDeprecated: use [
ClientBuilder::tls_crls_only()] instead.fn add_crls<impl IntoIterator<Item = CertificateRevocationList>: IntoIterator<Item = CertificateRevocationList>>(self: Self, crls: impl IntoIterator<Item = CertificateRevocationList>) -> ClientBuilderDeprecated: use [
ClientBuilder::tls_crls_only()] instead.fn identity(self: Self, identity: Identity) -> ClientBuilderSets the identity to be used for client certificate authentication.
Optional
This requires the optional
native-tlsorrustls(-...)feature to be enabled.fn tls_danger_accept_invalid_hostnames(self: Self, accept_invalid_hostname: bool) -> ClientBuilderControls 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, orrustls(-...)feature to be enabled.fn danger_accept_invalid_hostnames(self: Self, accept_invalid_hostname: bool) -> ClientBuilderDeprecated: use [
ClientBuilder::tls_danger_accept_invalid_hostnames()] instead.fn tls_danger_accept_invalid_certs(self: Self, accept_invalid_certs: bool) -> ClientBuilderControls 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, orrustls(-...)feature to be enabled.fn danger_accept_invalid_certs(self: Self, accept_invalid_certs: bool) -> ClientBuilderDeprecated: use [
ClientBuilder::tls_danger_accept_invalid_certs()] instead.fn tls_sni(self: Self, tls_sni: bool) -> ClientBuilderControls the use of TLS server name indication.
Defaults to
true.Optional
This requires the optional
default-tls,native-tls, orrustls(-...)feature to be enabled.fn tls_version_min(self: Self, version: Version) -> ClientBuilderSet 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_3will cause an error with thenative-tlsbackend. 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, orrustls(-...)feature to be enabled.fn min_tls_version(self: Self, version: Version) -> ClientBuilderDeprecated: use [
ClientBuilder::tls_version_min()] instead.fn tls_version_max(self: Self, version: Version) -> ClientBuilderSet the maximum allowed TLS version for connections.
By default, there's no maximum.
Errors
A value of
tls::Version::TLS_1_3will cause an error with thenative-tlsbackend. 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
rustlswith therustlsbackend.Optional
This requires the optional
default-tls,native-tls, orrustls(-...)feature to be enabled.fn max_tls_version(self: Self, version: Version) -> ClientBuilderDeprecated: use [
ClientBuilder::tls_version_max()] instead.fn tls_backend_rustls(self: Self) -> ClientBuilderForce using the Rustls TLS backend.
Since multiple TLS backends can be optionally enabled, this option will force the
rustlsbackend to be used for thisClient.Optional
This requires the optional
rustls(-...)feature to be enabled.fn use_rustls_tls(self: Self) -> ClientBuilderDeprecated: use [
ClientBuilder::tls_backend_rustls()] instead.fn tls_backend_preconfigured<impl Any: Any>(self: Self, tls: impl Any) -> ClientBuilderUse a preconfigured TLS backend.
If the passed
Anyargument is not a TLS backend that reqwest understands, theClientBuilderwill error when callingbuild.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
ClientBuilderto configure reqwest's TLS.Optional
This requires one of the optional features
native-tlsorrustls(-...)to be enabled.fn use_preconfigured_tls<impl Any: Any>(self: Self, tls: impl Any) -> ClientBuilderDeprecated: use [
ClientBuilder::tls_backend_preconfigured()] instead.fn tls_info(self: Self, tls_info: bool) -> ClientBuilderAdd TLS information as
TlsInfoextension to responses.Optional
This requires the optional
default-tls,native-tls, orrustls(-...)feature to be enabled.fn https_only(self: Self, enabled: bool) -> ClientBuilderRestrict the Client to be used with HTTPS only requests.
Defaults to false.
fn no_hickory_dns(self: Self) -> ClientBuilderDisables the hickory-dns async resolver.
This method exists even if the optional
hickory-dnsfeature is not enabled. This can be used to ensure aClientdoesn't use the hickory-dns async resolver even if another dependency were to enable the optionalhickory-dnsfeature.fn resolve(self: Self, domain: &str, addr: SocketAddr) -> ClientBuilderOverride DNS resolution for specific domains to a particular IP address.
Set the port to
0to 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]) -> ClientBuilderOverride DNS resolution for specific domains to particular IP addresses.
Set the port to
0to 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: IntoResolveOverride the DNS resolver implementation.
Overrides for specific names passed to
resolveandresolve_to_addrswill 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 + 'staticAdds a new Tower
Layerto the base connectorServicewhich is responsible for connection establishment.Each subsequent invocation of this function will wrap previous layers.
If configured, the
connect_timeoutwill be the outermost layer.Example usage:
use Duration; # let client = builder // resolved to outermost layer, meaning while we are waiting on concurrency limit .connect_timeout // underneath the concurrency check, so only after concurrency limit lets us through .connector_layer .connector_layer .build .unwrap;
impl ClientBuilder
fn new() -> SelfConstructs 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) -> TReturns 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) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses 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>