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. Pooled connections are reused only by requests with the same URI authority and the same address, so requests to one host with different addresses, or without one, never share a connection.

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.

The version does not select the transport protocol. On an HTTP/1 connection, HTTP/1.0 is sent as requested and any other version is sent as HTTP/1.1. An HTTP/2 connection always uses HTTP/2.

An HTTP/1.0 request closes the connection after the response unless keep-alive is requested, and a streaming body needs a Content-Length header because chunked coding is not available.

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. On HTTP/1 connections, the close, keep-alive and upgrade options of a Connection header set with header are applied the same way. HTTP/2 connections ignore the connection type.

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.

A streaming body (see send_stream) is sent with this length instead of chunked coding on HTTP/1 connections. Sending fails if the stream ends early or produces more data. A body with a known size is sent with its actual size and this value is ignored.

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.

When the request is sent, all cookies and every raw Cookie header value are merged into a single Cookie header.

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. It does not cover waiting for a pooled connection, connecting, sending the request body, or reading the response body; use MessageBody::timeout or JsonBody::timeout for the body. A zero duration disables only this 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, and a resulting URI longer than 65535 bytes, are stored and returned by the next send* call.

Source§

impl ClientRequest

Source

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

Sends the request with body.

Source

pub fn send_json<T: Serialize>( self, value: &T, ) -> impl Future<Output = Result<ClientResponse, Error<ClientError>>>

Serializes value as JSON and sends the request.

Source

pub fn send_form<T: Serialize>( self, value: &T, ) -> impl Future<Output = Result<ClientResponse, Error<ClientError>>>

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

Source

pub fn send_stream<T, E>( self, stream: T, ) -> impl Future<Output = 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 fn send( self, ) -> impl Future<Output = 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
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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.

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V