pub struct DefaultClient { /* private fields */ }
Expand description

An HTTP client, capable of sending Requests and running a middleware stack.

Can be optionally set with a base url.

§Examples

let client = surf::Client::new();
let res1 = client.recv_string(surf::get("https://httpbin.org/get"));
let res2 = client.recv_string(surf::get("https://httpbin.org/get"));
let (str1, str2) = futures_util::future::try_join(res1, res2).await?;

Implementations§

source§

impl Client

source

pub fn new() -> Client

Create a new Client instance.

§Examples
let client = surf::Client::new();

let req = surf::get("https://httpbin.org/get");
let res = client.send(req).await?;
source

pub fn with_http_client<C>(http_client: C) -> Client
where C: HttpClient,

Create a new Client instance with an http_client::HttpClient backend.

§Examples
use http_client::isahc::IsahcClient;
let client = surf::Client::with_http_client(IsahcClient::new());
source

pub fn with(self, middleware: impl Middleware) -> Client

Push middleware onto the middleware stack.

See the middleware submodule for more information on middleware.

§Examples
let req = surf::get("https://httpbin.org/get");
let client = surf::client()
    .with(surf::middleware::Redirect::default());
let res = client.send(req).await?;
source

pub async fn send(&self, req: impl Into<Request>) -> Result<Response, Error>

Send a Request using this client.

Client middleware is run before per-request middleware.

§Examples
let req = surf::get("https://httpbin.org/get");
let client = surf::client();
let res = client.send(req).await?;
source

pub async fn recv_bytes( &self, req: impl Into<Request> ) -> Result<Vec<u8>, Error>

Submit a Request and get the response body as bytes.

§Examples
let req = surf::get("https://httpbin.org/get");
let bytes = surf::client().recv_bytes(req).await?;
assert!(bytes.len() > 0);
source

pub async fn recv_string( &self, req: impl Into<Request> ) -> Result<String, Error>

Submit a Request and get the response body as a string.

§Examples
let req = surf::get("https://httpbin.org/get");
let string = surf::client().recv_string(req).await?;
assert!(string.len() > 0);
source

pub async fn recv_json<T>(&self, req: impl Into<Request>) -> Result<T, Error>

Submit a Request and decode the response body from json into a struct.

§Examples
#[derive(Deserialize, Serialize)]
struct Ip {
    ip: String
}

let req = surf::get("https://api.ipify.org?format=json");
let Ip { ip } = surf::client().recv_json(req).await?;
assert!(ip.len() > 10);
source

pub async fn recv_form<T>(&self, req: impl Into<Request>) -> Result<T, Error>

Submit a Request and decode the response body from form encoding into a struct.

§Errors

Any I/O error encountered while reading the body is immediately returned as an Err.

If the body cannot be interpreted as valid json for the target type T, an Err is returned.

§Examples
#[derive(Deserialize, Serialize)]
struct Body {
    apples: u32
}

let req = surf::get("https://api.example.com/v1/response");
let Body { apples } = surf::client().recv_form(req).await?;
source

pub fn get(&self, uri: impl AsRef<str>) -> RequestBuilder

Perform an HTTP GET request using the Client connection.

§Panics

This will panic if a malformed URL is passed.

§Errors

Returns errors from the middleware, http backend, and network sockets.

§Examples
let client = surf::client();
let string = client.get("https://httpbin.org/get").recv_string().await?;
source

pub fn head(&self, uri: impl AsRef<str>) -> RequestBuilder

Perform an HTTP HEAD request using the Client connection.

§Panics

This will panic if a malformed URL is passed.

§Errors

Returns errors from the middleware, http backend, and network sockets.

§Examples
let client = surf::client();
let string = client.head("https://httpbin.org/head").recv_string().await?;
source

pub fn post(&self, uri: impl AsRef<str>) -> RequestBuilder

Perform an HTTP POST request using the Client connection.

§Panics

This will panic if a malformed URL is passed.

§Errors

Returns errors from the middleware, http backend, and network sockets.

§Examples
let client = surf::client();
let string = client.post("https://httpbin.org/post").recv_string().await?;
source

pub fn put(&self, uri: impl AsRef<str>) -> RequestBuilder

Perform an HTTP PUT request using the Client connection.

§Panics

This will panic if a malformed URL is passed.

§Errors

Returns errors from the middleware, http backend, and network sockets.

§Examples
let client = surf::client();
let string = client.put("https://httpbin.org/put").recv_string().await?;
source

pub fn delete(&self, uri: impl AsRef<str>) -> RequestBuilder

Perform an HTTP DELETE request using the Client connection.

§Panics

This will panic if a malformed URL is passed.

§Errors

Returns errors from the middleware, http backend, and network sockets.

§Examples
let client = surf::client();
let string = client.delete("https://httpbin.org/delete").recv_string().await?;
source

pub fn connect(&self, uri: impl AsRef<str>) -> RequestBuilder

Perform an HTTP CONNECT request using the Client connection.

§Panics

This will panic if a malformed URL is passed.

§Errors

Returns errors from the middleware, http backend, and network sockets.

§Examples
let client = surf::client();
let string = client.connect("https://httpbin.org/connect").recv_string().await?;
source

pub fn options(&self, uri: impl AsRef<str>) -> RequestBuilder

Perform an HTTP OPTIONS request using the Client connection.

§Panics

This will panic if a malformed URL is passed.

§Errors

Returns errors from the middleware, http backend, and network sockets.

§Examples
let client = surf::client();
let string = client.options("https://httpbin.org/options").recv_string().await?;
source

pub fn trace(&self, uri: impl AsRef<str>) -> RequestBuilder

Perform an HTTP TRACE request using the Client connection.

§Panics

This will panic if a malformed URL is passed.

§Errors

Returns errors from the middleware, http backend, and network sockets.

§Examples
let client = surf::client();
let string = client.trace("https://httpbin.org/trace").recv_string().await?;
source

pub fn patch(&self, uri: impl AsRef<str>) -> RequestBuilder

Perform an HTTP PATCH request using the Client connection.

§Panics

This will panic if a malformed URL is passed.

§Errors

Returns errors from the middleware, http backend, and network sockets.

§Examples
let client = surf::client();
let string = client.patch("https://httpbin.org/patch").recv_string().await?;
source

pub fn request(&self, verb: Method, uri: impl AsRef<str>) -> RequestBuilder

Perform a HTTP request with the given verb using the Client connection.

§Panics

This will panic if a malformed URL is passed.

§Errors

Returns errors from the middleware, http backend, and network sockets.

§Examples
use http_types::Method;
let client = surf::client();
let req = client.request(Method::Get, "http://httpbin.org/get");
let res = client.send(req).await?;
source

pub fn set_base_url(&mut self, base: Url)

👎Deprecated since 6.5.0: Please use Config instead

Sets the base URL for this client. All request URLs will be relative to this URL.

Note: a trailing slash is significant. Without it, the last path component is considered to be a “file” name to be removed to get at the “directory” that is used as the base.

§Examples
let mut client = surf::client();
client.set_base_url(Url::parse("http://example.com/api/v1/")?);
client.get("posts.json").recv_json().await?; /// http://example.com/api/v1/posts.json
source

pub fn config(&self) -> &Config

Get the current configuration.

Trait Implementations§

source§

impl Clone for Client

source§

fn clone(&self) -> Client

Clones the Client.

This copies the middleware stack from the original, but shares the HttpClient and http client config of the original. Note that individual middleware in the middleware stack are still shared by reference.

1.0.0 · source§

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

Performs copy-assignment from source. Read more
source§

impl Debug for Client

source§

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

Formats the value using the given formatter. Read more
source§

impl Default for Client

source§

fn default() -> Client

Returns the “default value” for a type. Read more
source§

impl HttpClient for Client

§

type HeaderName = HeaderName

§

type Error = SurfStdError

§

type RequestBuilder = RequestBuilder

source§

fn build_header(name: &'static str) -> Result<Self::HeaderName, Self::Error>

Construct a HTTP client layer headername
source§

fn get(&self, uri: &str) -> Self::RequestBuilder

Make a get request
source§

fn post(&self, uri: &str) -> Self::RequestBuilder

Make a post request
source§

fn header( builder: Self::RequestBuilder, key: &Self::HeaderName, value: &str ) -> Self::RequestBuilder

Add a header to a request
source§

fn get_json<'async_trait, T>( req: Self::RequestBuilder ) -> Pin<Box<dyn Future<Output = Result<T, Self::Error>> + Send + 'async_trait>>
where T: 'async_trait + DeserializeOwned, Self: 'async_trait,

Make a get request and parse into JSON
source§

fn post_json<'life0, 'async_trait, T>( req: Self::RequestBuilder, content: &'life0 T ) -> Pin<Box<dyn Future<Output = Result<bool, Self::Error>> + Send + 'async_trait>>
where T: 'async_trait + Serialize + Sync, Self: 'async_trait, 'life0: 'async_trait,

Encode content into JSON and post to an endpoint. Returns the statuscode is_success() value.
source§

impl TryFrom<Config> for Client

§

type Error = <IsahcClient as TryFrom<Config>>::Error

The type returned in the event of a conversion error.
source§

fn try_from( config: Config ) -> Result<Client, <Client as TryFrom<Config>>::Error>

Performs the conversion.

Auto Trait Implementations§

§

impl Freeze for Client

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

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> 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> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

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>,

§

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>,

§

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<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

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