Skip to main content

ClientRequest

Struct ClientRequest 

Source
pub struct ClientRequest { /* private fields */ }
Expand description

An HTTP client request builder.

Builder methods configure the request and the send* methods consume it, send the request, and return a ClientResponse.

use ntex::client::Client;

#[ntex::main]
async fn main() {
   let response = Client::new()
        .get("http://www.rust-lang.org") // <- Create request builder
        .header("User-Agent", "ntex::web")
        .send()                          // <- Send http request
        .await;

   response.and_then(|response| {   // <- server http response
        println!("Response: {:?}", response);
        Ok(())
   });
}

Implementations§

Source§

impl ClientRequest

Source

pub fn uri<U>(self, uri: U) -> Self
where Url: TryFrom<U>, <Url as TryFrom<U>>::Error: Into<InvalidUrl>,

Sets the request URI.

URI conversion errors are stored and returned by the next send* call.

Source

pub fn get_uri(&self) -> &Url

Returns the request URI.

Source

pub fn address(self, addr: SocketAddr) -> Self

Sets the server socket address.

This address is used instead of resolving the URI host name.

Source

pub fn method(self, method: Method) -> Self

Sets the request method.

Source

pub fn get_method(&self) -> &Method

Returns the request method.

Source

pub fn version(self, version: Version) -> Self

Sets the request HTTP version.

By default, the version is selected from the negotiated transport protocol.

Source

pub fn get_version(&self) -> &Version

Returns the request HTTP version.

Source

pub fn headers(&self) -> &HeaderMap

Returns the request headers.

Source

pub fn headers_mut(&mut self) -> &mut HeaderMap

Returns mutable access to the request headers.

Source

pub fn header<K, V>(self, key: K, value: V) -> Self

Append a header.

The header is appended to any existing values with the same name. Use set_header to replace existing values.

Header conversion errors are stored and returned by the next send* call.

use ntex::{http, client::Client};

#[ntex::main]
async fn main() {
    let req = Client::new()
        .get("http://www.rust-lang.org")
        .header("X-TEST", "value")
        .header(http::header::CONTENT_TYPE, "application/json");
}
Source

pub fn set_header<K, V>(self, key: K, value: V) -> Self

Inserts a header, replacing existing values with the same name.

Header conversion errors are stored and returned by the next send* call.

Source

pub fn set_header_if_none<K, V>(self, key: K, value: V) -> Self

Inserts a header if the request does not already contain one with the same name.

Header conversion errors are stored and returned by the next send* call.

Source

pub fn set_connection_type(self, ctype: ConnectionType) -> Self

Sets the request connection type.

See RequestHead::set_connection_type() for how repeated calls are resolved.

Source

pub fn force_close(self) -> Self

Prevents an HTTP/1 connection from returning to the connection pool.

This setting affects only HTTP/1 connections.

Source

pub fn content_type<V>(self, value: V) -> Self

Sets the request content type.

Header conversion errors are stored and returned by the next send* call.

Source

pub fn content_length(self, len: u64) -> Self

Sets the request content length.

Source

pub fn basic_auth<U>(self, username: U, password: Option<&str>) -> Self
where U: Display,

Sets the HTTP basic authentication header.

Replaces any existing Authorization header, including a client default.

Source

pub fn bearer_auth<T>(self, token: T) -> Self
where T: Display,

Sets the HTTP bearer authentication header.

Replaces any existing Authorization header, including a client default.

Source

pub fn cookie<C>(self, cookie: C) -> Self
where C: Into<Cookie<'static>>,

Set a cookie.

use coo_kie as cookie;
use ntex::client::Client;

#[ntex::main]
async fn main() {
    let resp = Client::new().get("https://www.rust-lang.org")
        .cookie(
            cookie::Cookie::build(("name", "value"))
                .domain("www.rust-lang.org")
                .path("/")
                .secure(true)
                .http_only(true)
         )
         .send()
         .await;

    println!("Response: {:?}", resp);
}
Source

pub fn no_decompress(self) -> Self

Disables automatic decompression of the response body.

Source

pub fn timeout<T: Into<Millis>>(self, timeout: T) -> Self

Sets the response-header timeout for this request.

This overrides the client-wide timeout. The timeout covers receiving the response head after the request has been sent. A zero duration disables the timeout for this request.

The client-wide default is 5 seconds.

Source

pub fn if_true<F>(self, value: bool, f: F) -> Self

Applies f to this builder when value is true.

Source

pub fn if_some<T, F>(self, value: Option<T>, f: F) -> Self

Applies f and the contained value to this builder when value is Some.

Source

pub fn query<T: Serialize>(self, query: &T) -> Self

Serializes query and replaces the query component of the request URI.

Serialization errors are stored and returned by the next send* call.

Source§

impl ClientRequest

Source

pub async fn send_body<B>( self, body: B, ) -> Result<ClientResponse, Error<ClientError>>
where B: Into<Body>,

Sends the request with body.

Source

pub async fn send_json<T: Serialize>( self, value: &T, ) -> Result<ClientResponse, Error<ClientError>>

Serializes value as JSON and sends the request.

Source

pub async fn send_form<T: Serialize>( self, value: &T, ) -> Result<ClientResponse, Error<ClientError>>

Serializes value as a URL-encoded form and sends the request.

Source

pub async fn send_stream<T, E>( self, stream: T, ) -> Result<ClientResponse, Error<ClientError>>
where T: Stream<Item = Result<Bytes, E>> + Unpin + 'static, E: StdError + 'static,

Sends the request with a streaming body.

Source

pub async fn send(self) -> Result<ClientResponse, Error<ClientError>>

Sends the request with an empty body.

Trait Implementations§

Source§

impl Debug for ClientRequest

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

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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