pub struct HttpClient { /* private fields */ }
Expand description
An HTTP client for making requests.
An HttpClient
instance acts as a session for executing one or more HTTP
requests, and also allows you to set common protocol settings that should be
applied to all requests made with the client.
HttpClient
is entirely thread-safe, and implements both Send
and
Sync
. You are free to create clients outside the context of the “main”
thread, or move them between threads. You can even invoke many requests
simultaneously from multiple threads, since doing so doesn’t need a mutable
reference to the client. This is fairly cheap to do as well, since
internally requests use lock-free message passing to get things going.
The client maintains a connection pool internally and is not cheap to create, so we recommend creating a client once and re-using it throughout your code. Creating a new client for every request would decrease performance significantly, and might cause errors to occur under high workloads, caused by creating too many system resources like sockets or threads.
It is not universally true that you should use exactly one client instance in an application. All HTTP requests made with the same client will share any session-wide state, like cookies or persistent connections. It may be the case that it is better to create separate clients for separate areas of an application if they have separate concerns or are making calls to different servers. If you are creating an API client library, that might be a good place to maintain your own internal client.
§Examples
use chttp::prelude::*;
// Create a new client using reasonable defaults.
let client = HttpClient::default();
// Make some requests.
let mut response = client.get("https://example.org")?;
assert!(response.status().is_success());
println!("Response:\n{}", response.text()?);
Customizing the client configuration:
use chttp::{config::RedirectPolicy, prelude::*};
use std::time::Duration;
let client = HttpClient::builder()
.preferred_http_version(http::Version::HTTP_11)
.redirect_policy(RedirectPolicy::Limit(10))
.timeout(Duration::from_secs(20))
// May return an error if there's something wrong with our configuration
// or if the client failed to start up.
.build()?;
let response = client.get("https://example.org")?;
assert!(response.status().is_success());
See the documentation on HttpClientBuilder
for a comprehensive look at
what can be configured.
Implementations§
Source§impl HttpClient
impl HttpClient
Sourcepub fn new() -> Self
pub fn new() -> Self
Create a new HTTP client using the default configuration.
This is equivalent to the Default
implementation.
§Panics
Panics if any required internal systems fail to initialize. This might occur if creating a socket fails, spawning a thread fails, or if something else goes wrong.
Generally such a panic indicates an internal bug or an issue with system
configuration. If you need to catch these errors, you can use
HttpClientBuilder::build
instead.
Sourcepub fn builder() -> HttpClientBuilder
pub fn builder() -> HttpClientBuilder
Create a new HttpClientBuilder
for building a custom client.
Sourcepub fn get<U>(&self, uri: U) -> Result<Response<Body>, Error>where
Uri: HttpTryFrom<U>,
pub fn get<U>(&self, uri: U) -> Result<Response<Body>, Error>where
Uri: HttpTryFrom<U>,
Send a GET request to the given URI.
To customize the request further, see HttpClient::send
. To execute
the request asynchronously, see HttpClient::get_async
.
§Examples
use chttp::prelude::*;
let mut response = client.get("https://example.org")?;
println!("{}", response.text()?);
Sourcepub fn get_async<U>(&self, uri: U) -> ResponseFuture<'_> ⓘwhere
Uri: HttpTryFrom<U>,
pub fn get_async<U>(&self, uri: U) -> ResponseFuture<'_> ⓘwhere
Uri: HttpTryFrom<U>,
Send a GET request to the given URI asynchronously.
To customize the request further, see HttpClient::send_async
. To
execute the request synchronously, see HttpClient::get
.
Sourcepub fn head<U>(&self, uri: U) -> Result<Response<Body>, Error>where
Uri: HttpTryFrom<U>,
pub fn head<U>(&self, uri: U) -> Result<Response<Body>, Error>where
Uri: HttpTryFrom<U>,
Send a HEAD request to the given URI.
To customize the request further, see HttpClient::send
. To execute
the request asynchronously, see HttpClient::head_async
.
§Examples
let response = client.head("https://example.org")?;
println!("Page size: {:?}", response.headers()["content-length"]);
Sourcepub fn head_async<U>(&self, uri: U) -> ResponseFuture<'_> ⓘwhere
Uri: HttpTryFrom<U>,
pub fn head_async<U>(&self, uri: U) -> ResponseFuture<'_> ⓘwhere
Uri: HttpTryFrom<U>,
Send a HEAD request to the given URI asynchronously.
To customize the request further, see HttpClient::send_async
. To
execute the request synchronously, see HttpClient::head
.
Sourcepub fn post<U>(
&self,
uri: U,
body: impl Into<Body>,
) -> Result<Response<Body>, Error>where
Uri: HttpTryFrom<U>,
pub fn post<U>(
&self,
uri: U,
body: impl Into<Body>,
) -> Result<Response<Body>, Error>where
Uri: HttpTryFrom<U>,
Send a POST request to the given URI with a given request body.
To customize the request further, see HttpClient::send
. To execute
the request asynchronously, see HttpClient::post_async
.
§Examples
use chttp::prelude::*;
let client = HttpClient::default();
let response = client.post("https://httpbin.org/post", r#"{
"speed": "fast",
"cool_name": true
}"#)?;
Sourcepub fn post_async<U>(&self, uri: U, body: impl Into<Body>) -> ResponseFuture<'_> ⓘwhere
Uri: HttpTryFrom<U>,
pub fn post_async<U>(&self, uri: U, body: impl Into<Body>) -> ResponseFuture<'_> ⓘwhere
Uri: HttpTryFrom<U>,
Send a POST request to the given URI asynchronously with a given request body.
To customize the request further, see HttpClient::send_async
. To
execute the request synchronously, see HttpClient::post
.
Sourcepub fn put<U>(
&self,
uri: U,
body: impl Into<Body>,
) -> Result<Response<Body>, Error>where
Uri: HttpTryFrom<U>,
pub fn put<U>(
&self,
uri: U,
body: impl Into<Body>,
) -> Result<Response<Body>, Error>where
Uri: HttpTryFrom<U>,
Send a PUT request to the given URI with a given request body.
To customize the request further, see HttpClient::send
. To execute
the request asynchronously, see HttpClient::put_async
.
§Examples
use chttp::prelude::*;
let client = HttpClient::default();
let response = client.put("https://httpbin.org/put", r#"{
"speed": "fast",
"cool_name": true
}"#)?;
Sourcepub fn put_async<U>(&self, uri: U, body: impl Into<Body>) -> ResponseFuture<'_> ⓘwhere
Uri: HttpTryFrom<U>,
pub fn put_async<U>(&self, uri: U, body: impl Into<Body>) -> ResponseFuture<'_> ⓘwhere
Uri: HttpTryFrom<U>,
Send a PUT request to the given URI asynchronously with a given request body.
To customize the request further, see HttpClient::send_async
. To
execute the request synchronously, see HttpClient::put
.
Sourcepub fn delete<U>(&self, uri: U) -> Result<Response<Body>, Error>where
Uri: HttpTryFrom<U>,
pub fn delete<U>(&self, uri: U) -> Result<Response<Body>, Error>where
Uri: HttpTryFrom<U>,
Send a DELETE request to the given URI.
To customize the request further, see HttpClient::send
. To execute
the request asynchronously, see HttpClient::delete_async
.
Sourcepub fn delete_async<U>(&self, uri: U) -> ResponseFuture<'_> ⓘwhere
Uri: HttpTryFrom<U>,
pub fn delete_async<U>(&self, uri: U) -> ResponseFuture<'_> ⓘwhere
Uri: HttpTryFrom<U>,
Send a DELETE request to the given URI asynchronously.
To customize the request further, see HttpClient::send_async
. To
execute the request synchronously, see HttpClient::delete
.
Sourcepub fn send<B: Into<Body>>(
&self,
request: Request<B>,
) -> Result<Response<Body>, Error>
pub fn send<B: Into<Body>>( &self, request: Request<B>, ) -> Result<Response<Body>, Error>
Send an HTTP request and return the HTTP response.
The response body is provided as a stream that may only be consumed once.
This client’s configuration can be overridden for this request by
configuring the request using methods provided by the
RequestBuilderExt
trait.
Upon success, will return a Response
containing the status code,
response headers, and response body from the server. The Response
is
returned as soon as the HTTP response headers are received; the
connection will remain open to stream the response body in real time.
Dropping the response body without fully consume it will close the
connection early without downloading the rest of the response body.
Note that the actual underlying socket connection isn’t necessarily
closed on drop. It may remain open to be reused if pipelining is being
used, the connection is configured as keep-alive
, and so on.
Since the response body is streamed from the server, it may only be consumed once. If you need to inspect the response body more than once, you will have to either read it into memory or write it to a file.
To execute the request asynchronously, see HttpClient::send_async
.
§Examples
use chttp::prelude::*;
let client = HttpClient::default();
let request = Request::post("https://httpbin.org/post")
.header("Content-Type", "application/json")
.body(r#"{
"speed": "fast",
"cool_name": true
}"#)?;
let response = client.send(request)?;
assert!(response.status().is_success());
Sourcepub fn send_async<B: Into<Body>>(
&self,
request: Request<B>,
) -> ResponseFuture<'_> ⓘ
pub fn send_async<B: Into<Body>>( &self, request: Request<B>, ) -> ResponseFuture<'_> ⓘ
Send an HTTP request and return the HTTP response asynchronously.
See HttpClient::send
for further details.
§Examples
use chttp::prelude::*;
let client = HttpClient::default();
let request = Request::post("https://httpbin.org/post")
.header("Content-Type", "application/json")
.body(r#"{
"speed": "fast",
"cool_name": true
}"#)?;
let response = client.send_async(request).await?;
assert!(response.status().is_success());