Crate rquest

Source
Expand description

§rquest

An ergonomic all-in-one HTTP client for browser emulation with TLS, JA3/JA4, and HTTP/2 fingerprints.

Additional learning resources include:

§Emulation

The emulation module provides a way to simulate various browser TLS/HTTP2 fingerprints.

use rquest::Client;
use rquest_util::Emulation;

#[tokio::main]
async fn main() -> Result<(), rquest::Error> {
    // Build a client
    let client = Client::builder()
        .emulation(Emulation::Firefox136)
        .build()?;

    // Use the API you're already familiar with
    let resp = client.get("https://tls.peet.ws/api/all").send().await?;
    println!("{}", resp.text().await?);

    Ok(())
}

§Websocket

The websocket module provides a way to upgrade a connection to a websocket.

use futures_util::{SinkExt, StreamExt, TryStreamExt};
use http::header;
use rquest::{Client, Message};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), rquest::Error> {
   // Build a client
   let client = Client::builder()
       .cert_verification(false)
       .connect_timeout(Duration::from_secs(10))
       .build()?;

   // Use the API you're already familiar with
   let websocket = client
       .websocket("wss://echo.websocket.org")
       .header(header::USER_AGENT, env!("CARGO_PKG_NAME"))
       .send()
       .await?;

   assert_eq!(websocket.version(), http::Version::HTTP_11);

   let (mut tx, mut rx) = websocket.into_websocket().await?.split();

   tokio::spawn(async move {
       for i in 1..11 {
           if let Err(err) = tx.send(Message::text(format!("Hello, World! {i}"))).await {
               eprintln!("failed to send message: {err}");
           }
       }
   });

   while let Some(message) = rx.try_next().await? {
       if let Message::Text(text) = message {
           println!("received: {text}");
       }
   }

   Ok(())
}

§Making a GET request

Making a GET request is simple.

let body = rquest::Client::new()
    .get("https://www.rust-lang.org")
    .send()
    .await?
    .text()
    .await?;

println!("body = {:?}", body);

NOTE: If you plan to perform multiple requests, it is best to create a Client and reuse it, taking advantage of keep-alive connection pooling.

§Making POST requests (or setting request bodies)

There are several ways you can set the body of a request. The basic one is by using the body() method of a RequestBuilder. This lets you set the exact raw bytes of what the body should be. It accepts various types, including String and Vec<u8>. If you wish to pass a custom type, you can use the rquest::Body constructors.

let client = rquest::Client::new();
let res = client.post("http://httpbin.org/post")
    .body("the exact body that is sent")
    .send()
    .await?;

§Forms

It’s very common to want to send form data in a request body. This can be done with any type that can be serialized into form data.

This can be an array of tuples, or a HashMap, or a custom type that implements Serialize.

// This will POST a body of `foo=bar&baz=quux`
let params = [("foo", "bar"), ("baz", "quux")];
let client = rquest::Client::new();
let res = client.post("http://httpbin.org/post")
    .form(&params)
    .send()
    .await?;

§JSON

There is also a json method helper on the RequestBuilder that works in a similar fashion the form method. It can take any value that can be serialized into JSON. The feature json is required.

// This will POST a body of `{"lang":"rust","body":"json"}`
let mut map = HashMap::new();
map.insert("lang", "rust");
map.insert("body", "json");

let client = rquest::Client::new();
let res = client.post("http://httpbin.org/post")
    .json(&map)
    .send()
    .await?;

§Redirect Policies

By default, the client does not handle HTTP redirects. To customize this behavior, you can use redirect::Policy with ClientBuilder.

§Cookies

The automatic storing and sending of session cookies can be enabled with the cookie_store method on ClientBuilder.

§Proxies

NOTE: System proxies are enabled by default.

System proxies look in environment variables to set HTTP or HTTPS proxies.

HTTP_PROXY or http_proxy provide HTTP proxies for HTTP connections while HTTPS_PROXY or https_proxy provide HTTPS proxies for HTTPS connections. ALL_PROXY or all_proxy provide proxies for both HTTP and HTTPS connections. If both the all proxy and HTTP or HTTPS proxy variables are set the more specific HTTP or HTTPS proxies take precedence.

These can be overwritten by adding a Proxy to ClientBuilder i.e. let proxy = rquest::Proxy::http("https://secure.example")?; or disabled by calling ClientBuilder::no_proxy().

socks feature is required if you have configured socks proxy like this:

export https_proxy=socks5://127.0.0.1:1086
  • http:// is the scheme for http proxy
  • https:// is the scheme for https proxy
  • socks4:// is the scheme for socks4 proxy
  • socks4a:// is the scheme for socks4a proxy
  • socks5:// is the scheme for socks5 proxy
  • socks5h:// is the scheme for socks5h proxy

§TLS

By default, clients will utilize BoringSSL transport layer security to connect to HTTPS targets.

  • Various parts of TLS can also be configured or even disabled on the ClientBuilder.

§Certificate Store

By default, rquest uses Mozilla’s root certificates through the webpki-roots crate. This static root certificate bundle is not automatically updated and ignores any root certificates installed on the host. You can disable default-features to use the system’s default certificate path. Additionally, rquest provides a certificate store for users to customize and update certificates.

Custom Certificate Store verification supports Root CA certificates, peer certificates, and self-signed certificate SSL pinning.

§Optional Features

The following are a list of Cargo features that can be enabled or disabled:

  • full: Enables all optional features.
  • websocket: Provides websocket support.
  • cookies: Provides cookie session support.
  • cookies-preserve-order: uses indexmap::IndexMap in lieu of HashMap internally, so cookies are maintained in insertion/creation order.
  • cookies-abstract: Provides abstract cookie session support.
  • cookies-multiple: By default, all cookies are squeezed and sent. Enabling this feature will send multiple cookie headers.
  • gzip: Provides response body gzip decompression.
  • brotli: Provides response body brotli decompression.
  • zstd: Provides response body zstd decompression.
  • deflate: Provides response body deflate decompression.
  • json: Provides serialization and deserialization for JSON bodies.
  • multipart: Provides functionality for multipart forms.
  • stream: Adds support for futures::Stream.
  • socks: Provides SOCKS5 proxy support.
  • hickory-dns: Enables a hickory-dns async resolver instead of default threadpool using getaddrinfo.
  • native-roots: Use the native system root certificate store.
  • webpki-roots: Use the webpki-roots crate for root certificates.
  • apple-network-device-binding: Use the Apple Network Device Binding
  • http2-tracing: Enable HTTP/2 tracing.
  • internal_proxy_sys_no_cache: Use the internal proxy system with no cache.

Re-exports§

pub use self::tls::AlpnProtos;
pub use self::tls::AlpsProtos;
pub use self::tls::CertStore;
pub use self::tls::CertStoreBuilder;
pub use self::tls::Identity;
pub use self::tls::TlsConfig;
pub use self::tls::TlsInfo;
pub use self::tls::TlsVersion;
pub use hickory_resolver;

Modules§

cookie
HTTP Cookies
dns
DNS resolution
header
HTTP header types
multipart
multipart/form-data
redirect
Redirect Handling
tls
TLS configuration
websocket
WebSocket Upgrade

Structs§

Body
An asynchronous request body.
Client
An asynchronous Client to make Requests with.
ClientBuilder
A ClientBuilder can be used to create a Client with custom configuration.
ClientUpdate
A mutable reference to a ClientRef.
CloseCode
Status code used to indicate why an endpoint is closing the WebSocket connection.
CloseFrame
A struct representing the close command.
Dst
Destination of the request.
EmulationProvider
HTTP connection context that manages both HTTP and TLS configurations.
Error
The Errors that may occur when processing a Request.
ExtensionType
Extension types, to be used with ClientHello::get_extension.
Http1Builder
Http1 part of builder.
Http1Config
Configuration config for HTTP/1 connections.
Http2Builder
Http2 part of builder.
Http2Config
Configuration config for an HTTP/2 connection.
Method
The Request Method (VERB)
NoProxy
A configuration for filtering out requests that shouldn’t be proxied
Priority
The PRIORITY frame (type=0x2) specifies the sender-advised priority of a stream [Section 5.3]. It can be sent in any stream state, including idle or closed streams. [Section 5.3]: https://tools.ietf.org/html/rfc7540#section-5.3
Proxy
Configuration of a proxy that a Client should pass requests to.
Request
A request which can be executed with Client::execute().
RequestBuilder
A builder to construct the properties of a Request.
Response
A Response to a submitted Request.
SslCurve
A TLS Curve.
StatusCode
An HTTP status code (status-code in RFC 9110 et al.).
StreamDependency
Represents a stream dependency in HTTP/2 priority frames.
StreamId
A stream identifier, as described in Section 5.1.1 of RFC 7540.
Upgraded
An upgraded HTTP connection.
Url
A parsed URL record.
Utf8Bytes
UTF-8 wrapper for Bytes.
Version
Represents a version of the HTTP spec.
WebSocket
A websocket connection
WebSocketRequestBuilder
Wrapper for RequestBuilder that performs the websocket handshake when sent.
WebSocketResponse
The server’s response to the websocket upgrade request.

Enums§

CertCompressionAlgorithm
IANA assigned identifier of compression algorithm. See https://www.rfc-editor.org/rfc/rfc8879.html#name-compression-algorithms
Message
A WebSocket message.
PseudoOrder
Represents the order of HTTP/2 pseudo-header fields in the header block.
SettingsOrder
Represents the order of settings parameters in an HTTP/2 SETTINGS frame.

Traits§

EmulationProviderFactory
Trait defining the interface for providing an EmulationProvider.
IntoUrl
A trait to try to convert some type into a Url.
ResponseBuilderExt
Extension trait for http::response::Builder objects

Type Aliases§

Result
A Result alias where the Err case is rquest::Error.