pub struct HttpClient { /* private fields */ }Expand description
A runtime-agnostic HTTP client for sending HTTP requests.
HttpClient provides a high-level, fluent API for common HTTP operations over a
configurable transport. It runs on the Tokio runtime by default, but any runtime
and transport can be plugged in (see the custom module).
Tip: Cloning the client is cheap and results in instances that share the underlying connection pool and configuration.
§Examples
// Make a GET request
let response = client
.get("https://example.com")
.header(USER_AGENT, "MyApp/1.0")
.fetch()
.await?;
println!("Status: {}", response.status());See crate-level documentation for more details on available configuration options and advanced usage scenarios.
Implementations§
Source§impl HttpClient
impl HttpClient
Sourcepub fn request(
&self,
method: impl TryInto<Method, Error: Into<Error>>,
uri: impl TryInto<Uri, Error: Into<HttpError>>,
) -> HttpRequestBuilder<'_, Self>
pub fn request( &self, method: impl TryInto<Method, Error: Into<Error>>, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>
Creates a request builder with the specified method and URI.
This is the most flexible way to build requests. For common HTTP methods like GET or POST, you can use the dedicated helper methods instead.
§Performance tip
While you can provide strings for the method and URI, using pre-created
Method and Uri instances is more efficient as it avoids parsing overhead.
§Examples
use fetch::HttpClient;
// Using strings (convenient but with parsing overhead)
let response = client
.request("GET", "https://example.com/api")
.fetch()
.await?;
// Using pre-parsed values (more efficient) and additional customization
// before fetching the response.
let method = http::Method::GET;
let uri = "https://example.com/api".parse::<http::Uri>()?;
let response = client
.request(method, uri)
.header(USER_AGENT, "MyApp/1.0")
.fetch()
.await?;
Sourcepub fn get(
&self,
uri: impl TryInto<Uri, Error: Into<HttpError>>,
) -> HttpRequestBuilder<'_, Self>
pub fn get( &self, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>
Creates a GET request to the specified URI.
This is a convenient shortcut for request(Method::GET, uri).
§Performance tip
While you can provide a string for the URI, using a pre-created Uri
instance is more efficient as it avoids parsing overhead.
§Examples
// Basic GET request
let response: HttpResponse = client.get("https://example.com").fetch().await?;
// GET with additional customization
let response: HttpResponse = client
.get("https://api.example.com/users")
.header("X-API-Key", "my-key")
.fetch()
.await?;
// Get response as text
let body: Response<String> = client.get("https://example.com").fetch_text().await?;Sourcepub fn post(
&self,
uri: impl TryInto<Uri, Error: Into<HttpError>>,
) -> HttpRequestBuilder<'_, Self>
pub fn post( &self, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>
Creates a POST request to the specified URI.
This is a convenient shortcut for request(Method::POST, uri).
§Performance tip
While you can provide a string for the URI, using a pre-created Uri
instance is more efficient as it avoids parsing overhead.
§Examples
// Simple POST without a body
let response = client.post("https://api.example.com/users").fetch().await?;
// POST with text body and additional customization
let response = client
.post("https://api.example.com/users")
.header(USER_AGENT, "MyApp/1.0")
.text("my-text")
.fetch()
.await?;Sourcepub fn delete(
&self,
uri: impl TryInto<Uri, Error: Into<HttpError>>,
) -> HttpRequestBuilder<'_, Self>
pub fn delete( &self, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>
Creates a DELETE request to the specified URI.
This is a convenient shortcut for request(Method::DELETE, uri).
§Performance tip
While you can provide a string for the URI, using a pre-created Uri
instance is more efficient as it avoids parsing overhead.
§Examples
// Delete a resource
let response = client
.delete("https://api.example.com/users/123")
.header("Authorization", "Bearer token")
.fetch()
.await?;Sourcepub fn head(
&self,
uri: impl TryInto<Uri, Error: Into<HttpError>>,
) -> HttpRequestBuilder<'_, Self>
pub fn head( &self, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>
Creates a HEAD request to the specified URI.
This is a convenient shortcut for request(Method::HEAD, uri). HEAD requests are
similar to GET but return only headers without a body, useful for checking if a
resource exists or has been modified.
§Performance tip
While you can provide a string for the URI, using a pre-created Uri
instance is more efficient as it avoids parsing overhead.
§Examples
// Check if a resource exists without downloading it
let response = client
.head("https://example.com/large-file.zip")
.fetch()
.await?;Sourcepub fn put(
&self,
uri: impl TryInto<Uri, Error: Into<HttpError>>,
) -> HttpRequestBuilder<'_, Self>
pub fn put( &self, uri: impl TryInto<Uri, Error: Into<HttpError>>, ) -> HttpRequestBuilder<'_, Self>
Creates a PUT request to the specified URI.
This is a convenient shortcut for request(Method::PUT, uri).
§Performance tip
While you can provide a string for the URI, using a pre-created Uri
instance is more efficient as it avoids parsing overhead.
§Examples
// Simple PUT without a body
let response = client.put("https://api.example.com/users").fetch().await?;
// PUT with text body and additional customization
let response = client
.put("https://api.example.com/users")
.header(USER_AGENT, "MyApp/1.0")
.text("my-text")
.fetch()
.await?;Sourcepub fn patch(
&self,
uri: impl TryInto<Uri, Error = UriError>,
) -> HttpRequestBuilder<'_, Self>
pub fn patch( &self, uri: impl TryInto<Uri, Error = UriError>, ) -> HttpRequestBuilder<'_, Self>
Creates a PATCH request to the specified URI.
This is a convenient shortcut for request(Method::PATCH, uri). PATCH requests are used
for partial updates to resources, modifying only the specified fields rather than
replacing the entire resource.
§Performance tip
While you can provide a string for the URI, using a pre-created Uri
instance is more efficient as it avoids parsing overhead.
§Examples
// Partially update a resource with JSON payload
let response = client
.patch("https://api.example.com/users/123")
.header(USER_AGENT, "MyApp/1.0")
.text("some content")
.fetch()
.await?;Sourcepub fn with_base_uri(&self, base_uri: BaseUri) -> Self
pub fn with_base_uri(&self, base_uri: BaseUri) -> Self
Returns a new HttpClient that uses the given base URI for all requests.
The new client shares this client’s pipeline and configuration; only the base URI differs. The original client is left unchanged.
Source§impl HttpClient
impl HttpClient
Sourcepub fn builder_fake(
handler: impl Into<FakeHandler>,
deps: impl Into<FakeDeps>,
) -> HttpClientBuilder
pub fn builder_fake( handler: impl Into<FakeHandler>, deps: impl Into<FakeDeps>, ) -> HttpClientBuilder
Creates a builder for a test-friendly HTTP client with a fake handler.
Unlike HttpClient::new_fake, this method returns a builder that can be further
customized before constructing the client. Use this when you need more control
over the client’s configuration in test scenarios.
§Examples
async fn example() -> Result<(), Box<dyn std::error::Error>> {
let client = HttpClient::builder_fake(StatusCode::NOT_FOUND, FakeDeps::default())
.connect_timeout(Duration::from_millis(100))
.insecure_allow_http()
.build();
let response = client.get("http://test-url.local").fetch().await?;
assert_eq!(response.status(), StatusCode::NOT_FOUND);Available only when compiled with the test-util feature.
Sourcepub fn new_fake(handler: impl Into<FakeHandler>) -> Self
pub fn new_fake(handler: impl Into<FakeHandler>) -> Self
Creates a test-friendly HTTP client that uses mock responses.
This factory method provides a convenient way to create a client for testing without making real network requests. It automatically configures the builder with test-friendly defaults like allowing HTTP and using a minimal pipeline.
§Examples
// Create a client that always returns a specific status code
let client = HttpClient::new_fake(StatusCode::OK);
// Now you can use this client in tests without real network requests
let response = client.get("https://example.com").fetch().await?;
assert_eq!(response.status(), StatusCode::OK);Available only when compiled with the test-util feature.
Source§impl HttpClient
impl HttpClient
Sourcepub fn builder_tokio(deps: impl Into<TokioDeps>) -> HttpClientBuilder
pub fn builder_tokio(deps: impl Into<TokioDeps>) -> HttpClientBuilder
Creates a new HTTP client builder for the Tokio runtime.
This factory method provides a builder specifically configured for Tokio. Use this when working with Tokio-based applications.
Available only when compiled with the tokio feature and a TLS backend
(rustls and/or native-tls).
Sourcepub fn new_tokio() -> Self
pub fn new_tokio() -> Self
Creates a new HTTP client for the Tokio runtime.
This method creates a fully configured HTTP client instance with the default
configuration. Use builder_tokio if you want to customize the
client (e.g. supply a custom TokioDeps) before creating it.
Available only when compiled with the tokio feature and a TLS backend
(rustls and/or native-tls).
Trait Implementations§
Source§impl AsRef<HttpBodyBuilder> for HttpClient
impl AsRef<HttpBodyBuilder> for HttpClient
Source§fn as_ref(&self) -> &HttpBodyBuilder
fn as_ref(&self) -> &HttpBodyBuilder
Source§impl Clone for HttpClient
impl Clone for HttpClient
Source§fn clone(&self) -> HttpClient
fn clone(&self) -> HttpClient
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for HttpClient
impl Debug for HttpClient
Source§impl HasMemory for HttpClient
impl HasMemory for HttpClient
Source§fn memory(&self) -> impl MemoryShared
fn memory(&self) -> impl MemoryShared
Source§impl Memory for HttpClient
impl Memory for HttpClient
Auto Trait Implementations§
impl !RefUnwindSafe for HttpClient
impl !UnwindSafe for HttpClient
impl Freeze for HttpClient
impl Send for HttpClient
impl Sync for HttpClient
impl Unpin for HttpClient
impl UnsafeUnpin for HttpClient
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<In, Out, T> DynamicServiceExt<In, Out> for T
impl<In, Out, T> DynamicServiceExt<In, Out> for T
Source§fn into_dynamic(self) -> DynamicService<In, Out>
fn into_dynamic(self) -> DynamicService<In, Out>
DynamicService.