Struct isahc::HttpClientBuilder
source · [−]pub struct HttpClientBuilder { /* private fields */ }
Expand description
An HTTP client builder, capable of creating custom HttpClient
instances
with customized behavior.
Any option that can be configured per-request can also be configured on a
client builder as a default setting. Request configuration is provided by
the Configurable
trait, which is also available in the
prelude
module.
Examples
use isahc::{
config::{RedirectPolicy, VersionNegotiation},
prelude::*,
HttpClient,
};
use std::time::Duration;
let client = HttpClient::builder()
.timeout(Duration::from_secs(60))
.redirect_policy(RedirectPolicy::Limit(10))
.version_negotiation(VersionNegotiation::http2())
.build()?;
Implementations
sourceimpl HttpClientBuilder
impl HttpClientBuilder
sourcepub fn new() -> Self
pub fn new() -> Self
Create a new builder for building a custom client. All configuration will start out with the default values.
This is equivalent to the Default
implementation.
This is supported on crate feature cookies
only.
cookies
only.Enable persistent cookie handling for all requests using this client using a shared cookie jar.
Examples
use isahc::{prelude::*, HttpClient};
// Create a client with a cookie jar.
let client = HttpClient::builder()
.cookies()
.build()?;
// Make a request that sets a cookie.
let uri = "http://httpbin.org/cookies/set?foo=bar".parse()?;
client.get(&uri)?;
// Get the cookie from the cookie jar.
let cookie = client.cookie_jar()
.unwrap()
.get_by_name(&uri, "foo")
.unwrap();
assert_eq!(cookie, "bar");
Availability
This method is only available when the cookies
feature is enabled.
sourcepub fn max_connections(self, max: usize) -> Self
pub fn max_connections(self, max: usize) -> Self
Set a maximum number of simultaneous connections that this client is allowed to keep open at one time.
If set to a value greater than zero, no more than max
connections will
be opened at one time. If executing a new request would require opening
a new connection, then the request will stay in a “pending” state until
an existing connection can be used or an active request completes and
can be closed, making room for a new connection.
Setting this value to 0
disables the limit entirely.
This is an effective way of limiting the number of sockets or file descriptors that this client will open, though note that the client may use file descriptors for purposes other than just HTTP connections.
By default this value is 0
and no limit is enforced.
To apply a limit per-host, see
HttpClientBuilder::max_connections_per_host
.
sourcepub fn max_connections_per_host(self, max: usize) -> Self
pub fn max_connections_per_host(self, max: usize) -> Self
Set a maximum number of simultaneous connections that this client is allowed to keep open to individual hosts at one time.
If set to a value greater than zero, no more than max
connections will
be opened to a single host at one time. If executing a new request would
require opening a new connection, then the request will stay in a
“pending” state until an existing connection can be used or an active
request completes and can be closed, making room for a new connection.
Setting this value to 0
disables the limit entirely. By default this
value is 0
and no limit is enforced.
To set a global limit across all hosts, see
HttpClientBuilder::max_connections
.
sourcepub fn connection_cache_size(self, size: usize) -> Self
pub fn connection_cache_size(self, size: usize) -> Self
Set the size of the connection cache.
After requests are completed, if the underlying connection is reusable, it is added to the connection cache to be reused to reduce latency for future requests.
Setting the size to 0
disables connection caching for all requests
using this client.
By default this value is unspecified. A reasonable default size will be chosen.
sourcepub fn connection_cache_ttl(self, ttl: Duration) -> Self
pub fn connection_cache_ttl(self, ttl: Duration) -> Self
Set the maximum time-to-live (TTL) for connections to remain in the connection cache.
After requests are completed, if the underlying connection is reusable, it is added to the connection cache to be reused to reduce latency for future requests. This option controls how long such connections should be still considered valid before being discarded.
Old connections have a high risk of not working any more and thus attempting to use them wastes time if the server has disconnected.
The default TTL is 118 seconds.
sourcepub fn dns_cache<C>(self, cache: C) -> Self where
C: Into<DnsCache>,
pub fn dns_cache<C>(self, cache: C) -> Self where
C: Into<DnsCache>,
Configure DNS caching.
By default, DNS entries are cached by the client executing the request and are used until the entry expires. Calling this method allows you to change the entry timeout duration or disable caching completely.
Note that DNS entry TTLs are not respected, regardless of this setting.
By default caching is enabled with a 60 second timeout.
Examples
use isahc::{config::*, prelude::*, HttpClient};
use std::time::Duration;
let client = HttpClient::builder()
// Cache entries for 10 seconds.
.dns_cache(Duration::from_secs(10))
// Cache entries forever.
.dns_cache(DnsCache::Forever)
// Don't cache anything.
.dns_cache(DnsCache::Disable)
.build()?;
sourcepub fn dns_resolve(self, map: ResolveMap) -> Self
pub fn dns_resolve(self, map: ResolveMap) -> Self
Set a mapping of DNS resolve overrides.
Entries in the given map will be used first before using the default DNS resolver for host+port pairs.
Note that DNS resolving is only performed when establishing a new
Examples
use isahc::{config::ResolveMap, prelude::*, HttpClient};
use std::net::IpAddr;
let client = HttpClient::builder()
.dns_resolve(ResolveMap::new()
// Send requests for example.org on port 80 to 127.0.0.1.
.add("example.org", 80, [127, 0, 0, 1]))
.build()?;
sourcepub fn default_header<K, V>(self, key: K, value: V) -> Self where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<Error>,
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<Error>,
pub fn default_header<K, V>(self, key: K, value: V) -> Self where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<Error>,
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<Error>,
Add a default header to be passed with every request.
If a default header value is already defined for the given key, then a second header value will be appended to the list and multiple header values will be included in the request.
If any values are defined for this header key on an outgoing request, they will override any default header values.
If the header key or value are malformed, HttpClientBuilder::build
will return an error.
Examples
use isahc::{prelude::*, HttpClient};
let client = HttpClient::builder()
.default_header("some-header", "some-value")
.build()?;
sourcepub fn default_headers<K, V, I, P>(self, headers: I) -> Self where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<Error>,
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<Error>,
I: IntoIterator<Item = P>,
P: HeaderPair<K, V>,
pub fn default_headers<K, V, I, P>(self, headers: I) -> Self where
HeaderName: TryFrom<K>,
<HeaderName as TryFrom<K>>::Error: Into<Error>,
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<Error>,
I: IntoIterator<Item = P>,
P: HeaderPair<K, V>,
Set the default headers to include in every request, replacing any previously set default headers.
Headers defined on an individual request always override headers in the default map.
If any header keys or values are malformed, HttpClientBuilder::build
will return an error.
Examples
Set default headers from a slice:
use isahc::{prelude::*, HttpClient};
let mut builder = HttpClient::builder()
.default_headers(&[
("some-header", "value1"),
("some-header", "value2"),
("some-other-header", "some-other-value"),
])
.build()?;
Using an existing header map:
use isahc::{prelude::*, HttpClient};
let mut headers = http::HeaderMap::new();
headers.append("some-header".parse::<http::header::HeaderName>()?, "some-value".parse()?);
let mut builder = HttpClient::builder()
.default_headers(&headers)
.build()?;
Using a hashmap:
use isahc::{prelude::*, HttpClient};
use std::collections::HashMap;
let mut headers = HashMap::new();
headers.insert("some-header", "some-value");
let mut builder = HttpClient::builder()
.default_headers(headers)
.build()?;
sourcepub fn build(self) -> Result<HttpClient, Error>
pub fn build(self) -> Result<HttpClient, Error>
Build an HttpClient
using the configured options.
If the client fails to initialize, an error will be returned.
Trait Implementations
sourceimpl Configurable for HttpClientBuilder
impl Configurable for HttpClientBuilder
cookies
only.Set a cookie jar to use to accept, store, and supply cookies for incoming responses and outgoing requests. Read more
sourcefn timeout(self, timeout: Duration) -> Self
fn timeout(self, timeout: Duration) -> Self
Specify a maximum amount of time that a complete request/response cycle is allowed to take before being aborted. This includes DNS resolution, connecting to the server, writing the request, and reading the response. Read more
sourcefn connect_timeout(self, timeout: Duration) -> Self
fn connect_timeout(self, timeout: Duration) -> Self
Set a timeout for establishing connections to a host. Read more
sourcefn low_speed_timeout(self, low_speed: u32, timeout: Duration) -> Self
fn low_speed_timeout(self, low_speed: u32, timeout: Duration) -> Self
Specify a maximum amount of time where transfer rate can go below
a minimum speed limit. low_speed
is that limit in bytes/s. Read more
sourcefn version_negotiation(self, negotiation: VersionNegotiation) -> Self
fn version_negotiation(self, negotiation: VersionNegotiation) -> Self
Configure how the use of HTTP versions should be negotiated with the server. Read more
sourcefn redirect_policy(self, policy: RedirectPolicy) -> Self
fn redirect_policy(self, policy: RedirectPolicy) -> Self
Set a policy for automatically following server redirects. Read more
sourcefn auto_referer(self) -> Self
fn auto_referer(self) -> Self
Update the Referer
header automatically when following redirects.
sourcefn automatic_decompression(self, decompress: bool) -> Self
fn automatic_decompression(self, decompress: bool) -> Self
Enable or disable automatic decompression of the response body for
various compression algorithms as returned by the server in the
Content-Encoding
response header. Read more
sourcefn expect_continue<T>(self, expect: T) -> Self where
T: Into<ExpectContinue>,
fn expect_continue<T>(self, expect: T) -> Self where
T: Into<ExpectContinue>,
Configure the use of the Expect
request header when sending request
bodies with HTTP/1.1. Read more
sourcefn authentication(self, authentication: Authentication) -> Self
fn authentication(self, authentication: Authentication) -> Self
Set one or more default HTTP authentication methods to attempt to use when authenticating with the server. Read more
sourcefn credentials(self, credentials: Credentials) -> Self
fn credentials(self, credentials: Credentials) -> Self
Set the credentials to use for HTTP authentication. Read more
sourcefn tcp_keepalive(self, interval: Duration) -> Self
fn tcp_keepalive(self, interval: Duration) -> Self
Enable TCP keepalive with a given probe interval.
sourcefn tcp_nodelay(self) -> Self
fn tcp_nodelay(self) -> Self
Enables the TCP_NODELAY
option on connect.
sourcefn interface<I>(self, interface: I) -> Self where
I: Into<NetworkInterface>,
fn interface<I>(self, interface: I) -> Self where
I: Into<NetworkInterface>,
Bind local socket connections to a particular network interface. Read more
sourcefn ip_version(self, version: IpVersion) -> Self
fn ip_version(self, version: IpVersion) -> Self
Select a specific IP version when resolving hostnames. If a given hostname does not resolve to an IP address of the desired version, then the request will fail with a connection error. Read more
sourcefn dial<D>(self, dialer: D) -> Self where
D: Into<Dialer>,
fn dial<D>(self, dialer: D) -> Self where
D: Into<Dialer>,
Specify a socket to connect to instead of the using the host and port defined in the request URI. Read more
sourcefn proxy(self, proxy: impl Into<Option<Uri>>) -> Self
fn proxy(self, proxy: impl Into<Option<Uri>>) -> Self
Set a proxy to use for requests. Read more
sourcefn proxy_blacklist<I, T>(self, hosts: I) -> Self where
I: IntoIterator<Item = T>,
T: Into<String>,
fn proxy_blacklist<I, T>(self, hosts: I) -> Self where
I: IntoIterator<Item = T>,
T: Into<String>,
Disable proxy usage for the provided list of hosts. Read more
sourcefn proxy_authentication(self, authentication: Authentication) -> Self
fn proxy_authentication(self, authentication: Authentication) -> Self
Set one or more HTTP authentication methods to attempt to use when authenticating with a proxy. Read more
sourcefn proxy_credentials(self, credentials: Credentials) -> Self
fn proxy_credentials(self, credentials: Credentials) -> Self
Set the credentials to use for proxy authentication. Read more
sourcefn max_upload_speed(self, max: u64) -> Self
fn max_upload_speed(self, max: u64) -> Self
Set a maximum upload speed for the request body, in bytes per second. Read more
sourcefn max_download_speed(self, max: u64) -> Self
fn max_download_speed(self, max: u64) -> Self
Set a maximum download speed for the response body, in bytes per second. Read more
sourcefn ssl_client_certificate(self, certificate: ClientCertificate) -> Self
fn ssl_client_certificate(self, certificate: ClientCertificate) -> Self
Set a custom SSL/TLS client certificate to use for client connections. Read more
sourcefn ssl_ca_certificate(self, certificate: CaCertificate) -> Self
fn ssl_ca_certificate(self, certificate: CaCertificate) -> Self
Set a custom SSL/TLS CA certificate bundle to use for client connections. Read more
sourcefn ssl_ciphers<I, T>(self, ciphers: I) -> Self where
I: IntoIterator<Item = T>,
T: Into<String>,
fn ssl_ciphers<I, T>(self, ciphers: I) -> Self where
I: IntoIterator<Item = T>,
T: Into<String>,
Set a list of ciphers to use for SSL/TLS connections. Read more
sourcefn ssl_options(self, options: SslOption) -> Self
fn ssl_options(self, options: SslOption) -> Self
Set various options for this request that control SSL/TLS behavior. Read more
sourcefn title_case_headers(self, enable: bool) -> Self
fn title_case_headers(self, enable: bool) -> Self
Enable or disable sending HTTP header names in Title-Case instead of lowercase form. Read more
sourceimpl Debug for HttpClientBuilder
impl Debug for HttpClientBuilder
Auto Trait Implementations
impl !RefUnwindSafe for HttpClientBuilder
impl Send for HttpClientBuilder
impl Sync for HttpClientBuilder
impl Unpin for HttpClientBuilder
impl !UnwindSafe for HttpClientBuilder
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Instruments this type with the provided Span
, returning an
Instrumented
wrapper. Read more
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
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
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
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
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more