[][src]Module hreq_h1::client

Client implementation of the HTTP/1.1 protocol.

The client connection is split into two parts, one Connection, which encapsulates the actual transport, and a SendRequest which is used to send (multiple) requests over the connection.

Example

use hreq_h1::client;
use std::error::Error;
use async_std::net::TcpStream;
use http::Request;

#[async_std::main]
async fn main() -> Result<(), Box<dyn Error>> {
  // Establish TCP connection to the server.
  let tcp = TcpStream::connect("127.0.0.1:5928").await?;

  // h1 is the API handle to send requests
  let (mut h1, connection) = client::handshake(tcp);

  // Drive the connection independently of the API handle
  async_std::task::spawn(async move {
    if let Err(e) = connection.await {
      println!("Connection closed: {:?}", e);
    }
  });

  // POST request to. Note that body is sent below.
  let req = Request::post("http://myspecial.server/recv")
    .body(())?;

  let (res, mut send_body) = h1.send_request(req, false)?;

  send_body.send_data(b"This is the request body data", true).await?;

  let (head, mut body) = res.await?.into_parts();

  println!("Received response: {:?}", head);

  // Read response body into this buffer.
  let mut buf = [0_u8; 1024];
  loop {
     let amount = body.read(&mut buf).await?;

     println!("RX: {:?}", &buf[0..amount]);

     if amount == 0 {
       break;
     }
  }

  Ok(())
}

Structs

Connection

Future that manages the actual connection. Must be awaited to "drive" the connection.

ResponseFuture

Future for a http::Response<RecvStream>>

SendRequest

Sender of new requests.

Functions

handshake

Creates a new HTTP/1 client backed by some async io connection.