isahc

Struct HttpClient

Source
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 isahc::{prelude::*, HttpClient};

// Create a new client using reasonable defaults.
let client = HttpClient::new()?;

// 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 isahc::{
    config::{RedirectPolicy, VersionNegotiation},
    prelude::*,
    HttpClient,
};
use std::time::Duration;

let client = HttpClient::builder()
    .version_negotiation(VersionNegotiation::http11())
    .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

Source

pub fn new() -> Result<Self, Error>

Create a new HTTP client using the default configuration.

If the client fails to initialize, an error will be returned.

Source

pub fn builder() -> HttpClientBuilder

Create a new HttpClientBuilder for building a custom client.

Source

pub fn get<U>(&self, uri: U) -> Result<Response<Body>, Error>
where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<Error>,

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 isahc::{prelude::*, HttpClient};

let client = HttpClient::new()?;
let mut response = client.get("https://example.org")?;
println!("{}", response.text()?);
Source

pub fn get_async<U>(&self, uri: U) -> ResponseFuture<'_>
where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<Error>,

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.

Source

pub fn head<U>(&self, uri: U) -> Result<Response<Body>, Error>
where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<Error>,

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
use isahc::{prelude::*, HttpClient};

let client = HttpClient::new()?;
let response = client.head("https://example.org")?;
println!("Page size: {:?}", response.headers()["content-length"]);
Source

pub fn head_async<U>(&self, uri: U) -> ResponseFuture<'_>
where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<Error>,

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.

Source

pub fn post<U, B>(&self, uri: U, body: B) -> Result<Response<Body>, Error>
where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<Error>, B: Into<Body>,

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 isahc::{prelude::*, HttpClient};

let client = HttpClient::new()?;

let response = client.post("https://httpbin.org/post", r#"{
    "speed": "fast",
    "cool_name": true
}"#)?;
Source

pub fn post_async<U, B>(&self, uri: U, body: B) -> ResponseFuture<'_>
where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<Error>, B: Into<AsyncBody>,

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.

Source

pub fn put<U, B>(&self, uri: U, body: B) -> Result<Response<Body>, Error>
where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<Error>, B: Into<Body>,

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 isahc::{prelude::*, HttpClient};

let client = HttpClient::new()?;

let response = client.put("https://httpbin.org/put", r#"{
    "speed": "fast",
    "cool_name": true
}"#)?;
Source

pub fn put_async<U, B>(&self, uri: U, body: B) -> ResponseFuture<'_>
where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<Error>, B: Into<AsyncBody>,

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.

Source

pub fn delete<U>(&self, uri: U) -> Result<Response<Body>, Error>
where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<Error>,

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.

Source

pub fn delete_async<U>(&self, uri: U) -> ResponseFuture<'_>
where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<Error>,

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.

Source

pub fn send<B>(&self, request: Request<B>) -> Result<Response<Body>, Error>
where B: Into<Body>,

Send an HTTP request and return the HTTP response.

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 consuming it will close the connection early without downloading the rest of the response body.

The response body is provided as a stream that 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.

The response body is not a direct stream from the server, but uses its own buffering mechanisms internally for performance. It is therefore undesirable to wrap the body in additional buffering readers.

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.

This client’s configuration can be overridden for this request by configuring the request using methods provided by the Configurable trait.

To execute a request asynchronously, see HttpClient::send_async.

§Examples
use isahc::{prelude::*, HttpClient, Request};

let client = HttpClient::new()?;

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());
Source

pub fn send_async<B>(&self, request: Request<B>) -> ResponseFuture<'_>
where B: Into<AsyncBody>,

Send an HTTP request and return the HTTP response asynchronously.

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 consuming it will close the connection early without downloading the rest of the response body.

The response body is provided as a stream that 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.

The response body is not a direct stream from the server, but uses its own buffering mechanisms internally for performance. It is therefore undesirable to wrap the body in additional buffering readers.

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.

This client’s configuration can be overridden for this request by configuring the request using methods provided by the Configurable trait.

To execute a request synchronously, see HttpClient::send.

§Examples
use isahc::{prelude::*, HttpClient, Request};

let client = HttpClient::new()?;

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());

Trait Implementations§

Source§

impl Clone for HttpClient

Source§

fn clone(&self) -> HttpClient

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for HttpClient

Source§

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

Formats the value using the given formatter. 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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> 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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> 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