Request

Struct Request 

Source
pub struct Request<'a> { /* private fields */ }
Expand description

Relatively higher-level struct for making HTTP requests.

It creates stream (TcpStream or TlsStream) appropriate for the type of uri (http/https) By default it closes connection after completion of the response.

§Examples

use http_req::{request::Request, uri::Uri, response::StatusCode};
use std::convert::TryFrom;

let mut writer = Vec::new();
let uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();

let response = Request::new(&uri).send(&mut writer).unwrap();;
assert_eq!(response.status_code(), StatusCode::new(200));

Implementations§

Source§

impl<'a> Request<'a>

Source

pub fn new(uri: &'a Uri<'_>) -> Request<'a>

Creates new Request with default parameters

§Examples
use http_req::{request::Request, uri::Uri};
use std::convert::TryFrom;

let mut writer = Vec::new();
let uri: Uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();

let response = Request::new(&uri).send(&mut writer).unwrap();;
Examples found in repository?
examples/add_headers.rs (line 20)
8fn main() {
9    let mut writer = Vec::new();
10    let uri = Uri::try_from("http://eu.httpbin.org/get?msg=WasmEdge").unwrap();
11    // let uri = Uri::try_from("https://httpbin.org/get").unwrap(); // uncomment the line for https request
12
13    // add headers to the request
14    let mut headers = Headers::new();
15    headers.insert("Accept-Charset", "utf-8");
16    headers.insert("Accept-Language", "en-US");
17    headers.insert("Host", "rust-lang.org");
18    headers.insert("Connection", "Close");
19
20    Request::new(&uri)
21        .headers(headers)
22        .send(&mut writer)
23        .unwrap();
24
25    println!("{}", String::from_utf8_lossy(&writer));
26
27    // set version
28    Request::new(&uri)
29        .version(HttpVersion::Http10)
30        .send(&mut writer)
31        .unwrap();
32
33    println!("{}", String::from_utf8_lossy(&writer));
34}
Source

pub fn method<T>(&mut self, method: T) -> &mut Self
where Method: From<T>,

Sets request method

§Examples
use http_req::{request::{Request, Method}, uri::Uri};
use std::convert::TryFrom;

let mut writer = Vec::new();
let uri: Uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();

let response = Request::new(&uri)
    .method(Method::HEAD)
    .send(&mut writer)
    .unwrap();
Source

pub fn version<T>(&mut self, version: T) -> &mut Self
where HttpVersion: From<T>,

Sets HTTP version

§Examples
use http_req::{request::{Request, HttpVersion}, uri::Uri};
use std::convert::TryFrom;

let mut writer = Vec::new();
let uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();

let response = Request::new(&uri)
    .version(HttpVersion::Http10)
    .send(&mut writer)
    .unwrap();
Examples found in repository?
examples/add_headers.rs (line 29)
8fn main() {
9    let mut writer = Vec::new();
10    let uri = Uri::try_from("http://eu.httpbin.org/get?msg=WasmEdge").unwrap();
11    // let uri = Uri::try_from("https://httpbin.org/get").unwrap(); // uncomment the line for https request
12
13    // add headers to the request
14    let mut headers = Headers::new();
15    headers.insert("Accept-Charset", "utf-8");
16    headers.insert("Accept-Language", "en-US");
17    headers.insert("Host", "rust-lang.org");
18    headers.insert("Connection", "Close");
19
20    Request::new(&uri)
21        .headers(headers)
22        .send(&mut writer)
23        .unwrap();
24
25    println!("{}", String::from_utf8_lossy(&writer));
26
27    // set version
28    Request::new(&uri)
29        .version(HttpVersion::Http10)
30        .send(&mut writer)
31        .unwrap();
32
33    println!("{}", String::from_utf8_lossy(&writer));
34}
Source

pub fn headers<T>(&mut self, headers: T) -> &mut Self
where Headers: From<T>,

Replaces all it’s headers with headers passed to the function

§Examples
use http_req::{request::Request, uri::Uri, response::Headers};
use std::convert::TryFrom;

let mut writer = Vec::new();
let uri: Uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();

let mut headers = Headers::new();
headers.insert("Accept-Charset", "utf-8");
headers.insert("Accept-Language", "en-US");
headers.insert("Host", "rust-lang.org");
headers.insert("Connection", "Close");

let response = Request::new(&uri)
    .headers(headers)
    .send(&mut writer)
    .unwrap();;
Examples found in repository?
examples/add_headers.rs (line 21)
8fn main() {
9    let mut writer = Vec::new();
10    let uri = Uri::try_from("http://eu.httpbin.org/get?msg=WasmEdge").unwrap();
11    // let uri = Uri::try_from("https://httpbin.org/get").unwrap(); // uncomment the line for https request
12
13    // add headers to the request
14    let mut headers = Headers::new();
15    headers.insert("Accept-Charset", "utf-8");
16    headers.insert("Accept-Language", "en-US");
17    headers.insert("Host", "rust-lang.org");
18    headers.insert("Connection", "Close");
19
20    Request::new(&uri)
21        .headers(headers)
22        .send(&mut writer)
23        .unwrap();
24
25    println!("{}", String::from_utf8_lossy(&writer));
26
27    // set version
28    Request::new(&uri)
29        .version(HttpVersion::Http10)
30        .send(&mut writer)
31        .unwrap();
32
33    println!("{}", String::from_utf8_lossy(&writer));
34}
Source

pub fn header<T, U>(&mut self, key: &T, val: &U) -> &mut Self
where T: ToString + ?Sized, U: ToString + ?Sized,

Adds header to existing/default headers

§Examples
use http_req::{request::Request, uri::Uri};
use std::convert::TryFrom;

let mut writer = Vec::new();
let uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();

let response = Request::new(&uri)
    .header("Accept-Language", "en-US")
    .send(&mut writer)
    .unwrap();
Source

pub fn body(&mut self, body: &'a [u8]) -> &mut Self

Sets body for request

§Examples
use http_req::{request::{Request, Method}, uri::Uri};
use std::convert::TryFrom;

let mut writer = Vec::new();
let uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();
const body: &[u8; 27] = b"field1=value1&field2=value2";

let response = Request::new(&uri)
    .method(Method::POST)
    .header("Content-Length", &body.len())
    .body(body)
    .send(&mut writer)
    .unwrap();
Source

pub fn timeout<T>(&mut self, timeout: Option<T>) -> &mut Self
where Duration: From<T>,

Sets connection timeout of request.

§Examples
use std::{time::{Duration, Instant}, convert::TryFrom};
use http_req::{request::Request, uri::Uri};

let mut writer = Vec::new();
let uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();
const body: &[u8; 27] = b"field1=value1&field2=value2";
let timeout = Some(Duration::from_secs(3600));

let response = Request::new(&uri)
    .timeout(timeout)
    .send(&mut writer)
    .unwrap();
Source

pub fn connect_timeout<T>(&mut self, timeout: Option<T>) -> &mut Self
where Duration: From<T>,

Sets connect timeout while using internal TcpStream instance

  • If there is a timeout, it will be passed to TcpStream::connect_timeout.
  • If None is provided, TcpStream::connect will be used. A timeout will still be enforced by the operating system, but the exact value depends on the platform.
§Examples
use http_req::{request::Request, uri::Uri};
use std::{time::Duration, convert::TryFrom};

let mut writer = Vec::new();
let uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();
const time: Option<Duration> = Some(Duration::from_secs(10));

let response = Request::new(&uri)
    .connect_timeout(time)
    .send(&mut writer)
    .unwrap();
Source

pub fn read_timeout<T>(&mut self, timeout: Option<T>) -> &mut Self
where Duration: From<T>,

Sets read timeout on internal TcpStream instance

timeout will be passed to TcpStream::set_read_timeout.

§Examples
use http_req::{request::Request, uri::Uri};
use std::{time::Duration, convert::TryFrom};

let mut writer = Vec::new();
let uri: Uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();
const time: Option<Duration> = Some(Duration::from_secs(15));

let response = Request::new(&uri)
    .read_timeout(time)
    .send(&mut writer)
    .unwrap();
Source

pub fn write_timeout<T>(&mut self, timeout: Option<T>) -> &mut Self
where Duration: From<T>,

Sets write timeout on internal TcpStream instance

timeout will be passed to TcpStream::set_write_timeout.

§Examples
use http_req::{request::Request, uri::Uri};
use std::{time::Duration, convert::TryFrom};

let mut writer = Vec::new();
let uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();
const time: Option<Duration> = Some(Duration::from_secs(5));

let response = Request::new(&uri)
    .write_timeout(time)
    .send(&mut writer)
    .unwrap();
Source

pub fn root_cert_file_pem(&mut self, file_path: &'a Path) -> &mut Self

Add a file containing the PEM-encoded certificates that should be added in the trusted root store.

Source

pub fn send<T: Write>(&self, writer: &mut T) -> Result<Response, Error>

Sends HTTP request.

Creates TcpStream (and wraps it with TlsStream if needed). Writes request message to created stream. Returns response for this request. Writes response’s body to writer.

§Examples
use http_req::{request::Request, uri::Uri};
use std::convert::TryFrom;

let mut writer = Vec::new();
let uri: Uri = Uri::try_from("https://www.rust-lang.org/learn").unwrap();

let response = Request::new(&uri).send(&mut writer).unwrap();
Examples found in repository?
examples/add_headers.rs (line 22)
8fn main() {
9    let mut writer = Vec::new();
10    let uri = Uri::try_from("http://eu.httpbin.org/get?msg=WasmEdge").unwrap();
11    // let uri = Uri::try_from("https://httpbin.org/get").unwrap(); // uncomment the line for https request
12
13    // add headers to the request
14    let mut headers = Headers::new();
15    headers.insert("Accept-Charset", "utf-8");
16    headers.insert("Accept-Language", "en-US");
17    headers.insert("Host", "rust-lang.org");
18    headers.insert("Connection", "Close");
19
20    Request::new(&uri)
21        .headers(headers)
22        .send(&mut writer)
23        .unwrap();
24
25    println!("{}", String::from_utf8_lossy(&writer));
26
27    // set version
28    Request::new(&uri)
29        .version(HttpVersion::Http10)
30        .send(&mut writer)
31        .unwrap();
32
33    println!("{}", String::from_utf8_lossy(&writer));
34}

Trait Implementations§

Source§

impl<'a> Clone for Request<'a>

Source§

fn clone(&self) -> Request<'a>

Returns a duplicate 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<'a> Debug for Request<'a>

Source§

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

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

impl<'a> PartialEq for Request<'a>

Source§

fn eq(&self, other: &Request<'a>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<'a> StructuralPartialEq for Request<'a>

Auto Trait Implementations§

§

impl<'a> Freeze for Request<'a>

§

impl<'a> RefUnwindSafe for Request<'a>

§

impl<'a> Send for Request<'a>

§

impl<'a> Sync for Request<'a>

§

impl<'a> Unpin for Request<'a>

§

impl<'a> UnwindSafe for Request<'a>

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, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> 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.