### Client::get() example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html A simple example of making a `GET` request to a specified URL using the `get()` convenience method. ```rust let url = "http://httpbin.org/get"; let resp = client.get(url).send().await.unwrap(); println!("{:?}", resp); ``` -------------------------------- ### get() example Source: https://docs.rs/wreq/5.3.0/wreq/header/struct.OccupiedEntry.html Example of how to get a reference to the first value in an occupied entry. ```Rust let mut map = HeaderMap::new(); map.insert(HOST, "hello.world".parse().unwrap()); if let Entry::Occupied(mut e) = map.entry("host") { assert_eq!(e.get(), &"hello.world"); e.append("hello.earth".parse().unwrap()); assert_eq!(e.get(), &"hello.world"); } ``` -------------------------------- ### Making a GET request Source: https://docs.rs/wreq/5.3.0/src/wreq/lib.rs.html Basic example of making a GET request and retrieving the response body as text. ```rust # async fn run() -> Result<(), wreq::Error> { let body = wreq::Client::new() .get("https://www.rust-lang.org") .send() .await? .text() .await?; println!("body = {:?}", body); # Ok(()) # } ``` -------------------------------- ### Uri::path example Source: https://docs.rs/wreq/5.3.0/wreq/struct.Dst.html Example demonstrating how to get the path component of a Uri. ```rust let uri: Uri = "/hello/world".parse().unwrap(); assert_eq!(uri.path(), "/hello/world"); ``` ```rust let uri: Uri = "http://example.org/hello/world".parse().unwrap(); assert_eq!(uri.path(), "/hello/world"); ``` -------------------------------- ### Send Example Source: https://docs.rs/wreq/5.3.0/wreq/struct.RequestBuilder.html A basic example of sending a GET request and receiving a response. ```rust let response = wreq::Client::new() .get("https://hyper.rs") .send() .await?; ``` -------------------------------- ### Examples Source: https://docs.rs/wreq/5.3.0/wreq/struct.Method.html Demonstrates usage of the Method type, including conversion from bytes, checking idempotency, and getting the string representation. ```rust use http::Method; assert_eq!(Method::GET, Method::from_bytes(b"GET").unwrap()); assert!(Method::GET.is_idempotent()); assert_eq!(Method::POST.as_str(), "POST"); ``` -------------------------------- ### Example Source: https://docs.rs/wreq/5.3.0/wreq/struct.StatusCode.html Demonstrates getting the string representation of a StatusCode. ```rust let status = http::StatusCode::OK; assert_eq!(status.as_str(), "200"); ``` -------------------------------- ### CertStoreBuilder Example Source: https://docs.rs/wreq/5.3.0/wreq/tls/struct.CertStoreBuilder.html Example of how to use the CertStoreBuilder to create a CertStore. ```rust use wreq::CertStore; let store = CertStore::builder() .add_cert(&der_or_pem_cert) .add_der_cert(&der_cert) .add_pem_cert(&pem_cert) .set_default_paths() .build()?; ``` -------------------------------- ### to_file_path example Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Example of using Url::to_file_path. ```rust let path = url.to_file_path(); ``` -------------------------------- ### interface example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html This example demonstrates binding to a network interface using SO_BINDTODEVICE. ```rust let interface = "lo"; let client = wreq::Client::builder() .interface(interface) .build().unwrap(); ``` -------------------------------- ### Example of implementing EmulationProviderFactory Source: https://docs.rs/wreq/5.3.0/src/wreq/client/emulation.rs.html This example demonstrates how to implement the `EmulationProviderFactory` trait for a custom type. ```rust use wreq::{EmulationProviderFactory, EmulationProvider}; struct MyEmulationProvider; impl EmulationProviderFactory for MyEmulationProvider { fn emulation(self) -> EmulationProvider { EmulationProvider::default() } } let provider = MyEmulationProvider.emulation(); ``` -------------------------------- ### from_file_path examples Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Examples of using Url::from_file_path on Unix-like platforms. ```rust use url::Url; let url = Url::from_file_path("/tmp/foo.txt")?; assert_eq!(url.as_str(), "file:///tmp/foo.txt"); let url = Url::from_file_path("../foo.txt"); assert!(url.is_err()); let url = Url::from_file_path("https://google.com/"); assert!(url.is_err()); ``` -------------------------------- ### ClientBuilder Example with connect_timeout Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html Example of configuring a connection timeout using ClientBuilder. ```rust let client = wreq::Client::builder() // resolved to outermost layer, meaning while we are waiting on concurrency limit .connect_timeout(Duration::from_millis(200)) ``` -------------------------------- ### Sending a Request Source: https://docs.rs/wreq/5.3.0/src/wreq/client/request.rs.html Example of how to send a GET request using RequestBuilder and await the response. ```rust # use wreq::Error; # # async fn run() -> Result<(), Error> { let response = wreq::Client::new() .get("https://hyper.rs") .send() .await?; # Ok(()) # } ``` -------------------------------- ### Uri::host example Source: https://docs.rs/wreq/5.3.0/wreq/struct.Dst.html Example demonstrating how to extract the host from a Uri. ```rust let uri: Uri = "http://example.org:80/hello/world".parse().unwrap(); assert_eq!(uri.host(), Some("example.org")); ``` ```rust let uri: Uri = "/hello/world".parse().unwrap(); assert!(uri.host().is_none()); ``` -------------------------------- ### VacantEntry::into_key() example Source: https://docs.rs/wreq/5.3.0/wreq/header/struct.VacantEntry.html Example demonstrating how to take ownership of the key. ```rust let mut map = HeaderMap::new(); if let Entry::Vacant(v) = map.entry("x-hello") { assert_eq!(v.into_key().as_str(), "x-hello"); } ``` -------------------------------- ### CertStoreBuilder Example Source: https://docs.rs/wreq/5.3.0/src/wreq/tls/x509/store.rs.html Demonstrates how to build a CertStore by adding certificates and setting default paths. ```rust #![allow(missing_debug_implementations)] use std::{fmt::Debug, path::Path}; use boring2::x509::store::{X509Store, X509StoreBuilder}; use super::{Certificate, CertificateInput, Identity}; /// A builder for constructing a `CertStore`. /// /// This builder provides methods to add certificates to the store from various formats, /// and to set default paths for the certificate store. Once all desired certificates /// have been added, the `build` method can be used to create the `CertStore`. /// /// # Example /// /// ```rust /// use wreq::CertStore; /// /// let store = CertStore::builder() /// .add_cert(&der_or_pem_cert) /// .add_der_cert(&der_cert) /// .add_pem_cert(&pem_cert) /// .set_default_paths() /// .build()?; /// ``` #[derive(Default)] pub struct CertStoreBuilder { identity: Option, builder: Option>, } impl CertStoreBuilder { /// Adds an identity to the certificate store. #[inline] pub fn identity(mut self, identity: Identity) -> Self { self.identity = Some(identity); self } /// Adds a DER/PEM-encoded certificate to the certificate store. /// /// # Parameters /// /// - `cert`: A reference to a byte slice containing the DER/PEM-encoded certificate. #[inline] pub fn add_cert<'c, C>(self, cert: C) -> Self where C: Into>, { self.parse_cert(cert, Certificate::from) } /// Adds a DER-encoded certificate to the certificate store. /// /// # Parameters /// /// - `cert`: A reference to a byte slice containing the DER-encoded certificate. #[inline] pub fn add_der_cert<'c, C>(self, cert: C) -> Self where C: Into>, { self.parse_cert(cert, Certificate::from_der) } /// Adds a PEM-encoded certificate to the certificate store. /// /// # Parameters /// /// - `cert`: A reference to a byte slice containing the PEM-encoded certificate. #[inline] pub fn add_pem_cert<'c, C>(self, cert: C) -> Self where C: Into>, { self.parse_cert(cert, Certificate::from_pem) } /// Adds multiple DER/PEM-encoded certificates to the certificate store. /// /// # Parameters /// /// - `certs`: An iterator over DER/PEM-encoded certificates. #[inline] pub fn add_certs<'c, I>(self, certs: I) -> Self where I: IntoIterator, I::Item: Into>, { self.parse_certs(certs, Certificate::from) } /// Adds multiple DER-encoded certificates to the certificate store. /// /// # Parameters /// /// - `certs`: An iterator over DER-encoded certificates. #[inline] pub fn add_der_certs<'c, I>(self, certs: I) -> Self where I: IntoIterator, I::Item: Into>, { self.parse_certs(certs, Certificate::from_der) } /// Adds multiple PEM-encoded certificates to the certificate store. /// /// # Parameters /// /// - `certs`: An iterator over PEM-encoded certificates. #[inline] pub fn add_pem_certs<'c, I>(self, certs: I) -> Self where I: IntoIterator, I::Item: Into>, { self.parse_certs(certs, Certificate::from_pem) } /// Adds a PEM-encoded certificate stack to the certificate store. /// /// # Parameters /// /// - `certs`: A PEM-encoded certificate stack. pub fn add_stack_pem_certs(mut self, certs: C) -> Self where C: AsRef<[u8]>, { if let Ok(builder) = self.get_or_init() { let result = Certificate::stack_from_pem(certs.as_ref()) .and_then(|certs| process_certs(certs.into_iter(), builder)); if let Err(err) = result { self.builder = Some(Err(err)); } } self } /// Adds PEM-encoded certificates from a file to the certificate store. /// /// This method reads the file at the specified path, expecting it to contain a PEM-encoded /// certificate stack, and then adds the certificates to the store. /// /// # Parameters /// /// - `path`: A reference to a path of the PEM file. pub fn add_file_pem_certs

(mut self, path: P) -> Self where P: AsRef, { match std::fs::read(path) { Ok(data) => return self.add_stack_pem_certs(data), Err(err) => { ``` -------------------------------- ### Making a GET request Source: https://docs.rs/wreq/5.3.0/index.html Making a GET request is simple. ```Rust let body = wreq::Client::new() .get("https://www.rust-lang.org") .send() .await? .text() .await?; println!("body = {:?}", body); ``` -------------------------------- ### Client::builder() example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html This example demonstrates how to obtain a `ClientBuilder` to configure a `Client` without panicking on initialization errors. This is useful for handling potential TLS or resolver configuration failures as `Result`s. ```rust let client = wreq::Client::builder() .build() .expect("Failed to build client"); // Use the client to make requests... ``` -------------------------------- ### key() example Source: https://docs.rs/wreq/5.3.0/wreq/header/struct.OccupiedEntry.html Example of how to get the key of an occupied entry. ```Rust let mut map = HeaderMap::new(); map.insert(HOST, "world".parse().unwrap()); if let Entry::Occupied(e) = map.entry("host") { assert_eq!("host", e.key()); } ``` -------------------------------- ### Client::new() example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html This example shows how to create a new `Client` instance using the `new()` method. It panics if TLS or resolver configuration fails. ```rust let client = wreq::Client::new(); // Use the client to make requests... ``` -------------------------------- ### get() example Source: https://docs.rs/wreq/5.3.0/wreq/websocket/struct.Utf8Bytes.html Demonstrates how to get a subslice of str non-panicking. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### remove() example Source: https://docs.rs/wreq/5.3.0/wreq/header/struct.OccupiedEntry.html Example of removing an occupied entry and getting the first value. ```Rust let mut map = HeaderMap::new(); map.insert(HOST, "world".parse().unwrap()); if let Entry::Occupied(e) = map.entry("host") { let mut prev = e.remove(); assert_eq!("world", prev); } assert!(!map.contains_key("host")); ``` -------------------------------- ### Example of building an EmulationProvider Source: https://docs.rs/wreq/5.3.0/src/wreq/client/emulation.rs.html This example shows how to create an `EmulationProvider` instance using its builder pattern and configuring TLS settings. ```rust use wreq::EmulationProvider; use wreq::TlsConfig; let provider = EmulationProvider::builder() .tls_config(TlsConfig::default()) .build(); ``` -------------------------------- ### Uri::scheme example Source: https://docs.rs/wreq/5.3.0/wreq/struct.Dst.html Example showing how to retrieve the scheme of a Uri. ```rust use http::uri::{Scheme, Uri}; let uri: Uri = "http://example.org/hello/world".parse().unwrap(); assert_eq!(uri.scheme(), Some(&Scheme::HTTP)); ``` ```rust let uri: Uri = "/hello/world".parse().unwrap(); assert!(uri.scheme().is_none()); ``` -------------------------------- ### VacantEntry::insert_entry() example Source: https://docs.rs/wreq/5.3.0/wreq/header/struct.VacantEntry.html Example demonstrating how to insert a value and get an OccupiedEntry. ```rust let mut map = HeaderMap::new(); if let Entry::Vacant(v) = map.try_entry("x-hello").unwrap() { let mut e = v.try_insert_entry("world".parse().unwrap()).unwrap(); e.insert("world2".parse().unwrap()); } assert_eq!(map["x-hello"], "world2"); ``` -------------------------------- ### SSL Pinning Example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html Demonstrates how to configure SSL pinning with a list of certificates. ```rust use wreq::Client; let client = Client::builder() .ssl_pinning(vec![ include_bytes!("certs/server_cert.pem"), include_bytes!("certs/intermediate_cert.pem"), ]) .build() .unwrap(); ``` -------------------------------- ### Get the full response text. Source: https://docs.rs/wreq/5.3.0/src/wreq/client/response.rs.html This example demonstrates how to get the full response body as text. ```rust # async fn run() -> Result<(), Box> { let content = wreq::Client::new() .get("http://httpbin.org/range/26") .send() .await? .text() .await?; println!("text: {content:?}"); # Ok(()) # } ``` -------------------------------- ### Client Builder Example Source: https://docs.rs/wreq/5.3.0/src/wreq/util/client/mod.rs.html Example of configuring a new Client with a builder, setting pool idle timeout and enabling HTTP/2. ```Rust use std::time::Duration; use crate::util::client::Client; use crate::util::rt::TokioExecutor; let client = Client::builder(TokioExecutor::new()) .pool_idle_timeout(Duration::from_secs(30)) .http2_only(true) .build_http(); let infer: Client<_, http_body_util::Full> = client; ``` -------------------------------- ### Client::post() example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html An example of making a `POST` request to a URL. The `RequestBuilder` returned by `post()` can be further configured before sending. ```rust let url = "http://httpbin.org/post"; let resp = client.post(url).body("some data").send().await.unwrap(); println!("{:?}", resp); ``` -------------------------------- ### Uri::scheme_str example Source: https://docs.rs/wreq/5.3.0/wreq/struct.Dst.html Example of getting the scheme of a Uri as a string slice. ```rust let uri: Uri = "http://example.org/hello/world".parse().unwrap(); assert_eq!(uri.scheme_str(), Some("http")); ``` -------------------------------- ### Client Configuration Example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html This snippet shows how to configure a client with various options, including DNS overrides, timeouts, keep-alive settings, and TLS configurations. ```rust if !config.dns_overrides.is_empty() { resolver = Arc::new(DnsResolverWithOverrides::new( resolver, config.dns_overrides, )); } let mut http = HttpConnector::new_with_resolver(DynResolver::new(resolver)); http.set_connect_timeout(config.connect_timeout); http.set_keepalive_interval(config.tcp_keepalive_interval); http.set_keepalive_retries(config.tcp_keepalive_retries); #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] http.set_tcp_user_timeout(config.tcp_user_timeout); let tls = { let mut tls_config = config.tls_config.unwrap_or_default(); if let Some(alpn_protos) = config.alpn_protos { tls_config.alpn_protos = alpn_protos; } if let Some(tls_sni) = config.tls_sni { tls_config.tls_sni = tls_sni; } if let Some(verify_hostname) = config.verify_hostname { tls_config.verify_hostname = verify_hostname; } if let Some(cert_verification) = config.cert_verification { tls_config.cert_verification = cert_verification; } if config.cert_store.is_some() { tls_config.cert_store = config.cert_store.clone(); } if config.min_tls_version.is_some() { tls_config.min_tls_version = config.min_tls_version; } if config.max_tls_version.is_some() { tls_config.max_tls_version = config.max_tls_version; } TlsConnector::new(tls_config)? }; ConnectorBuilder::new(http, tls, config.nodelay, config.tls_info) .timeout(config.connect_timeout) .keepalive(config.tcp_keepalive) .verbose(config.connection_verbose) .build(config.connector_layers) }; Ok(Client { inner: Arc::new(ArcSwap::from_pointee(ClientRef { accepts: config.accepts, #[cfg(any(feature = "cookies", feature = "cookies-abstract"))] cookie_store: config.cookie_store, hyper: config.builder.build(connector), headers: config.headers, headers_order: config.headers_order, redirect: config.redirect_policy, referer: config.referer, request_timeout: config.timeout, read_timeout: config.read_timeout, https_only: config.https_only, http2_max_retry_count: config.http2_max_retry_count, proxies, proxies_maybe_http_auth, network_scheme: config.network_scheme, alpn_protos: config.alpn_protos, tls_sni: config.tls_sni, verify_hostname: config.verify_hostname, cert_verification: config.cert_verification, root_cert_store: config.cert_store, min_tls_version: config.min_tls_version, max_tls_version: config.max_tls_version, })), }) } ``` -------------------------------- ### Proxy Configuration Example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html Demonstrates how to configure proxy settings for the HTTP client. ```rust use wreq::Client; use wreq::Proxy; let proxy = Proxy::http("http://proxy:8080").unwrap(); let client = Client::builder().proxy(proxy).build().unwrap(); let client = Client::builder().proxy("http://proxy2:8080").build().unwrap(); ``` -------------------------------- ### Client::request() example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html This example shows how to initiate a request with a specific HTTP method and URL using the `request()` method, which returns a `RequestBuilder` for further customization. ```rust let url = "http://httpbin.org/put"; let resp = client.request(wreq::Method::PUT, url).send().await.unwrap(); println!("{:?}", resp); ``` -------------------------------- ### remove_entry() example Source: https://docs.rs/wreq/5.3.0/wreq/header/struct.OccupiedEntry.html Example of removing an occupied entry and getting the key and the first value. ```Rust let mut map = HeaderMap::new(); map.insert(HOST, "world".parse().unwrap()); if let Entry::Occupied(e) = map.entry("host") { let (key, mut prev) = e.remove_entry(); assert_eq!("host", key.as_str()); assert_eq!("world", prev); } assert!(!map.contains_key("host")); ``` -------------------------------- ### insert() example Source: https://docs.rs/wreq/5.3.0/wreq/header/struct.OccupiedEntry.html Example of setting the value of an occupied entry and getting the previous value. ```Rust let mut map = HeaderMap::new(); map.insert(HOST, "hello.world".parse().unwrap()); if let Entry::Occupied(mut e) = map.entry("host") { let mut prev = e.insert("earth".parse().unwrap()); assert_eq!("hello.world", prev); } assert_eq!("earth", map["host"]); ``` -------------------------------- ### HTTPS Proxy Example Source: https://docs.rs/wreq/5.3.0/src/wreq/proxy.rs.html Shows how to set up an HTTPS proxy. This is useful when the proxy server itself uses HTTPS. ```Rust use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { let proxy = reqwest::Proxy::https("http://127.0.0.1:8080")?; let client = reqwest::Client::builder() .proxy(proxy) .build()?; let res = client.get("http://httpbin.org/ip").send().await?; println!("{:?}", res.text().await?); Ok(()) } ``` -------------------------------- ### get_mut() example Source: https://docs.rs/wreq/5.3.0/wreq/header/struct.OccupiedEntry.html Example of how to get a mutable reference to the first value in an occupied entry. ```Rust let mut map = HeaderMap::default(); map.insert(HOST, "hello.world".to_string()); if let Entry::Occupied(mut e) = map.entry("host") { e.get_mut().push_str("-2"); assert_eq!(e.get(), &"hello.world-2"); } ``` -------------------------------- ### Sending a Request with Client Source: https://docs.rs/wreq/5.3.0/src/wreq/util/client/mod.rs.html This example demonstrates how to create a `Client` and use it to send a POST request to `http://httpbin.org/post` with a JSON body. ```rust # # fn run () { use hyper2::{Method, Request}; use crate::util::client::Client; use http_body_util::Full; use crate::util::rt::TokioExecutor; use bytes::Bytes; let client: Client<_, Full> = Client::builder(TokioExecutor::new()).build_http(); let req: Request> = Request::builder() .method(Method::POST) .uri("http://httpbin.org/post") .body(Full::from("Hallo!")) .expect("request builder"); let future = client.request(req); # } # fn main() {} ``` -------------------------------- ### VacantEntry::key() example Source: https://docs.rs/wreq/5.3.0/wreq/header/struct.VacantEntry.html Example demonstrating how to get a reference to the entry's key. ```rust let mut map = HeaderMap::new(); assert_eq!(map.entry("x-hello").key().as_str(), "x-hello"); ``` -------------------------------- ### Proxy with Authentication Example Source: https://docs.rs/wreq/5.3.0/src/wreq/proxy.rs.html Illustrates how to configure a proxy that requires authentication. This example sets up a proxy with a username and password. ```Rust use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { let proxy = reqwest::Proxy::http("http://user:password@127.0.0.1:8080")?; let client = reqwest::Client::builder() .proxy(proxy) .build()?; let res = client.get("http://httpbin.org/ip").send().await?; println!("{:?}", res.text().await?); Ok(()) } ``` -------------------------------- ### Get response body as Bytes Source: https://docs.rs/wreq/5.3.0/wreq/struct.Response.html Example of how to get the full response body as a Bytes object. ```rust let bytes = wreq::Client::new() .get("http://httpbin.org/ip") .send() .await? .bytes() .await?; println!("bytes: {bytes:?}"); ``` -------------------------------- ### Basic Authentication Example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/request.rs.html Demonstrates how to use the `basic_auth` method to set up basic HTTP authentication for a DELETE request. ```rust use wreq::Error; # async fn run() -> Result<(), Error> { let client = wreq::Client::new(); let resp = client.delete("http://httpbin.org/delete") .basic_auth("admin", Some("good password")) .send() .await?; # Ok(()) # } ``` -------------------------------- ### insert_mult() example Source: https://docs.rs/wreq/5.3.0/wreq/header/struct.OccupiedEntry.html Example of setting the value of an occupied entry and getting an iterator over previous values. ```Rust let mut map = HeaderMap::new(); map.insert(HOST, "world".parse().unwrap()); map.append(HOST, "world2".parse().unwrap()); if let Entry::Occupied(mut e) = map.entry("host") { let mut prev = e.insert_mult("earth".parse().unwrap()); assert_eq!("world", prev.next().unwrap()); assert_eq!("world2", prev.next().unwrap()); assert!(prev.next().is_none()); } assert_eq!("earth", map["host"]); ``` -------------------------------- ### match_indices examples Source: https://docs.rs/wreq/5.3.0/wreq/websocket/struct.Utf8Bytes.html Examples of using `match_indices` to find the start index and value of each match. ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` -------------------------------- ### Inner::setup_ssl Source: https://docs.rs/wreq/5.3.0/src/wreq/tls/conn/boring.rs.html Sets up the SSL configuration for a given URI and host. ```rust fn setup_ssl(&self, uri: &Uri, host: &str) -> Result { let mut conf = self.ssl.configure()?; if let Some(ref callback) = self.callback { callback(&mut conf, uri)?; } if let Some(authority) = uri.authority() { let key = SessionKey(authority.clone()); if let Some(ref cache) = self.cache { if let Some(session) = cache.lock().get(&key) { unsafe { conf.set_session(&session)?; } if self.skip_session_ticket { conf.skip_session_ticket()?; } } } let idx = key_index()?; conf.set_ex_data(idx, key); } let mut ssl = conf.into_ssl(host)?; if let Some(ref ssl_callback) = self.ssl_callback { ssl_callback(&mut ssl, uri)?; } Ok(ssl) } ``` -------------------------------- ### Box::from_raw Example: Manual creation using global allocator Source: https://docs.rs/wreq/5.3.0/wreq/dns/type.Addrs.html Example demonstrating manual creation of a Box from scratch using the global allocator and Box::from_raw. ```Rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Get response text Source: https://docs.rs/wreq/5.3.0/wreq/struct.Response.html Example of how to get the full response text, with BOM sniffing and malformed sequence replacement. ```rust let content = wreq::Client::new() .get("http://httpbin.org/range/26") .send() .await? .text() .await?; println!("text: {content:?}"); ``` -------------------------------- ### rmatch_indices examples Source: https://docs.rs/wreq/5.3.0/wreq/websocket/struct.Utf8Bytes.html Examples of using `rmatch_indices` to find the start index and value of each match in reverse order. ```rust let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect(); assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]); let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect(); assert_eq!(v, [(4, "abc"), (1, "abc")]); let v: Vec<_> = "ababa".rmatch_indices("aba").collect(); assert_eq!(v, [(2, "aba")]); // only the last `aba` ``` -------------------------------- ### Making a GET request Source: https://docs.rs/wreq/5.3.0/wreq A simple example of making a GET request and retrieving the response body as text. ```rust let body = wreq::Client::new() .get("https://www.rust-lang.org") .send() .await?; .text() .await?; println!("body = {:?}", body); ``` -------------------------------- ### Port Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Examples of getting the port number from a URL. ```rust use url::Url; let url = Url::parse("https://example.com")?; assert_eq!(url.port(), None); let url = Url::parse("https://example.com:443/")?; assert_eq!(url.port(), None); let url = Url::parse("ssh://example.com:22")?; assert_eq!(url.port(), Some(22)); ``` -------------------------------- ### set_password example Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Shows how to set a password for a URL, including cases where it's not possible (e.g., mailto URLs) and successful updates. ```rust use url::{Url, ParseError}; let mut url = Url::parse("mailto:rmz@example.com")?; let result = url.set_password(Some("secret_password")); assert!(result.is_err()); let mut url = Url::parse("ftp://user1:secret1@example.com")?; let result = url.set_password(Some("secret_password")); assert_eq!(url.password(), Some("secret_password")); let mut url = Url::parse("ftp://user2:@example.com")?; let result = url.set_password(Some("secret2")); assert!(result.is_ok()); assert_eq!(url.password(), Some("secret2")); ``` -------------------------------- ### Example Source: https://docs.rs/wreq/5.3.0/wreq/struct.StatusCode.html Demonstrates getting the u16 representation of a StatusCode. ```rust let status = http::StatusCode::OK; assert_eq!(status.as_u16(), 200); ``` -------------------------------- ### Url::scheme() example Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Demonstrates retrieving the scheme from a URL. ```rust use url::Url; let url = Url::parse("file:///tmp/foo")?; assert_eq!(url.scheme(), "file"); ``` -------------------------------- ### Get response text with specified charset Source: https://docs.rs/wreq/5.3.0/wreq/struct.Response.html Example of how to get the full response text with a default encoding specified. Requires the 'charset' feature. ```rust let content = wreq::Client::new() .get("http://httpbin.org/range/26") .send() .await? .text_with_charset("utf-8") .await?; println!("text: {content:?}"); ``` -------------------------------- ### Host Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Examples of getting the parsed host representation of a URL. ```rust use url::Url; let url = Url::parse("https://127.0.0.1/index.html")?; assert!(url.host().is_some()); let url = Url::parse("ftp://rms@example.com")?; assert!(url.host().is_some()); let url = Url::parse("unix:/run/foo.socket")?; assert!(url.host().is_none()); let url = Url::parse("data:text/plain,Stuff")?; assert!(url.host().is_none()); ``` -------------------------------- ### Client Builder `build` method Source: https://docs.rs/wreq/5.3.0/src/wreq/util/client/mod.rs.html Combines the configuration of this builder with a connector to create a `Client`. ```rust pub fn build(&self, connector: C) -> Client where C: Connect + Clone, B: Body + Send, B::Data: Send, { let exec = self.exec.clone(); let timer = self.pool_timer.clone(); Client { config: self.client_config, exec: exec.clone(), h1_builder: self.h1_builder.clone(), h2_builder: self.h2_builder.clone(), connector, pool: pool::Pool::new(self.pool_config, exec, timer), } } ``` -------------------------------- ### len() example Source: https://docs.rs/wreq/5.3.0/wreq/websocket/struct.Utf8Bytes.html Demonstrates how to get the length of a Utf8Bytes in bytes. ```rust let len = "foo".len(); assert_eq!(3, len); assert_eq!("ƒoo".len(), 4); // fancy f! assert_eq!("ƒoo".chars().count(), 3); ``` -------------------------------- ### Host String Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Examples of getting the host string representation of a URL. ```rust use url::Url; let url = Url::parse("https://127.0.0.1/index.html")?; assert_eq!(url.host_str(), Some("127.0.0.1")); let url = Url::parse("ftp://rms@example.com")?; assert_eq!(url.host_str(), Some("example.com")); let url = Url::parse("unix:/run/foo.socket")?; assert_eq!(url.host_str(), None); let url = Url::parse("data:text/plain,Stuff")?; assert_eq!(url.host_str(), None); ``` -------------------------------- ### from_raw_in Example 2 Source: https://docs.rs/wreq/5.3.0/wreq/dns/type.Addrs.html Manually creates a Box from scratch by using the system allocator. ```rust #![feature(allocator_api, slice_ptr_get)] use std::alloc::{Allocator, Layout, System}; unsafe { let ptr = System.allocate(Layout::new::())?.as_mut_ptr() as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw_in(ptr, System); } ``` -------------------------------- ### Getting the fragment identifier of a URL Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Examples of retrieving the fragment identifier from a URL. ```rust use url::Url; let url = Url::parse("https://example.com/data.csv#row=4")?; assert_eq!(url.fragment(), Some("row=4")); let url = Url::parse("https://example.com/data.csv#cell=4,1-6,2")?; assert_eq!(url.fragment(), Some("cell=4,1-6,2")); ``` -------------------------------- ### Getting the query string of a URL Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Examples of retrieving the query string from a URL. ```rust use url::Url; fn run() -> Result<(), ParseError> { let url = Url::parse("https://example.com/products?page=2")?; let query = url.query(); assert_eq!(query, Some("page=2")); let url = Url::parse("https://example.com/products")?; let query = url.query(); assert!(query.is_none()); let url = Url::parse("https://example.com/?country=español")?; let query = url.query(); assert_eq!(query, Some("country=espa%C3%B1ol")); } ``` -------------------------------- ### Box::from_non_null Example: Manual creation using global allocator Source: https://docs.rs/wreq/5.3.0/wreq/dns/type.Addrs.html Example demonstrating manual creation of a Box from scratch using the global allocator and Box::from_non_null. ```Rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::Как) .expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### local_address example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html This example shows how to bind the client to a specific local IP address. ```rust use std::net::IpAddr; let local_addr = IpAddr::from([12, 4, 1, 8]); let client = wreq::Client::builder() .local_address(local_addr) .build().unwrap(); ``` -------------------------------- ### Getting the path of a URL Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Examples demonstrating how to extract the path component from a URL. ```rust use url::{Url, ParseError}; let url = Url::parse("https://example.com/api/versions?page=2")?; assert_eq!(url.path(), "/api/versions"); let url = Url::parse("https://example.com")?; assert_eq!(url.path(), "/"); let url = Url::parse("https://example.com/countries/việt nam")?; assert_eq!(url.path(), "/countries/vi%E1%BB%87t%20nam"); ``` -------------------------------- ### Domain Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Examples of getting the domain name from a URL, if it is a domain and not an IP address. ```rust use url::Url; let url = Url::parse("https://127.0.0.1/")?; assert_eq!(url.domain(), None); let url = Url::parse("mailto:rms@example.net")?; assert_eq!(url.domain(), None); let url = Url::parse("https://example.com/")?; assert_eq!(url.domain(), Some("example.com")); ``` -------------------------------- ### SOCKS Proxy Configuration Example Source: https://docs.rs/wreq/5.3.0/wreq/index.html Example of how to configure a SOCKS proxy using environment variables, requiring the 'socks' feature. ```bash export https_proxy=socks5://127.0.0.1:1086 ``` -------------------------------- ### Setting Default Headers Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html Example demonstrating how to set default headers for a wreq client, including sensitive headers like Authorization. ```rust use wreq::header; use std::sync::Arc; async fn doc() -> Result<(), wreq::Error> { let mut headers = header::HeaderMap::new(); headers.insert("X-MY-HEADER", header::HeaderValue::from_static("value")); // Consider marking security-sensitive headers with `set_sensitive`. let mut auth_value = header::HeaderValue::from_static("secret"); auth_value.set_sensitive(true); headers.insert(header::AUTHORIZATION, auth_value); // get a client builder let client = wreq::Client::builder() .default_headers(headers) .build()?; let res = client.get("https://www.rust-lang.org").send().await?; Ok(()) } ``` -------------------------------- ### Url::origin() with other scheme Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Example of getting the origin for a URL with a custom scheme. ```rust use url::{Host, Origin, Url}; let url = Url::parse("foo:bar")?; assert!(!url.origin().is_tuple()); ``` -------------------------------- ### Multipart Form Data Example Source: https://docs.rs/wreq/5.3.0/src/wreq/client/request.rs.html Shows how to construct and send a multipart/form-data request using the `multipart` method with a `Form` object. ```rust use wreq::Error; # async fn run() -> Result<(), Error> { let client = wreq::Client::new(); let form = wreq::multipart::Form::new() .text("key3", "value3") .text("key4", "value4"); let response = client.post("your url") .multipart(form) .send() .await?; # Ok(()) # } ``` -------------------------------- ### Getting path segments of a URL Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Examples showing how to iterate over the path segments of a URL. ```rust use url::Url; let url = Url::parse("https://example.com/foo/bar")?; let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?; assert_eq!(path_segments.next(), Some("foo")); assert_eq!(path_segments.next(), Some("bar")); assert_eq!(path_segments.next(), None); let url = Url::parse("https://example.com")?; let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?; assert_eq!(path_segments.next(), Some("")); assert_eq!(path_segments.next(), None); let url = Url::parse("data:text/plain,HelloWorld")?; assert!(url.path_segments().is_none()); let url = Url::parse("https://example.com/countries/việt nam")?; let mut path_segments = url.path_segments().ok_or_else(|| "cannot be base")?; assert_eq!(path_segments.next(), Some("countries")); assert_eq!(path_segments.next(), Some("vi%E1%BB%87t%20nam")); ``` -------------------------------- ### Url::origin() with blob scheme Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Example of getting the origin for a URL with a blob scheme. ```rust use url::{Host, Origin, Url}; let url = Url::parse("blob:https://example.com/foo")?; assert_eq!(url.origin(), Origin::Tuple("https".into(), Host::Domain("example.com".into()), 443)); ``` -------------------------------- ### set_scheme examples Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Provides examples of changing a URL's scheme, including successful changes between common schemes, changes between custom schemes, and various failure scenarios. ```rust use url::Url; let mut url = Url::parse("https://example.net")?; let result = url.set_scheme("http"); assert_eq!(url.as_str(), "http://example.net/"); assert!(result.is_ok()); ``` ```rust use url::Url; let mut url = Url::parse("foo://example.net")?; let result = url.set_scheme("bar"); assert_eq!(url.as_str(), "bar://example.net"); assert!(result.is_ok()); ``` ```rust use url::Url; let mut url = Url::parse("https://example.net")?; let result = url.set_scheme("foõ"); assert_eq!(url.as_str(), "https://example.net/"); assert!(result.is_err()); ``` ```rust use url::Url; let mut url = Url::parse("mailto:rms@example.net")?; let result = url.set_scheme("https"); assert_eq!(url.as_str(), "mailto:rms@example.net"); assert!(result.is_err()); ``` ```rust use url::Url; let mut url = Url::parse("foo://example.net")?; let result = url.set_scheme("https"); assert_eq!(url.as_str(), "foo://example.net"); assert!(result.is_err()); ``` ```rust use url::Url; let mut url = Url::parse("http://example.net")?; let result = url.set_scheme("foo"); assert_eq!(url.as_str(), "http://example.net/"); assert!(result.is_err()); ``` -------------------------------- ### Url::origin() with ftp scheme Source: https://docs.rs/wreq/5.3.0/wreq/struct.Url.html Example of getting the origin for a URL with an ftp scheme. ```rust use url::{Host, Origin, Url}; let url = Url::parse("ftp://example.com/foo")?; assert_eq!(url.origin(), Origin::Tuple("ftp".into(), Host::Domain("example.com".into()), 21)); ``` -------------------------------- ### http1 closure configuration Source: https://docs.rs/wreq/5.3.0/src/wreq/client/http.rs.html This example demonstrates how to configure the HTTP/1 builder using a closure. ```rust let client = wreq::Client::builder() .http1(|http1| { http1.http09_responses(true); }) .build()?; ```