### GET / (ureq::get) Source: https://docs.rs/ureq/latest/ureq/fn.get.html Initiates a GET request using the ureq library. ```APIDOC ## GET ureq::get ### Description Make a GET request. This function runs on a use-once Agent. ### Method GET ### Parameters #### Path Parameters - **uri** (T) - Required - The URI to request. Must be convertible to a Uri type. ### Response - **RequestBuilder** - Returns a request builder configured for a GET request. ``` -------------------------------- ### Proxy Example: Create from URI Source: https://docs.rs/ureq/latest/src/ureq/proxy.rs.html Demonstrates creating a proxy instance by parsing a URI string. ```rust let proxy = Proxy::new("http://localhost:8080").unwrap(); ``` -------------------------------- ### Proxy Example: Read from Environment Source: https://docs.rs/ureq/latest/src/ureq/proxy.rs.html Illustrates how to attempt to create a proxy configuration by reading from environment variables. ```rust if let Some(proxy) = Proxy::try_from_env() { // Use proxy from environment } ``` -------------------------------- ### POST with Redirect to GET Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Demonstrates a POST request with a body that results in a redirect to a GET request. Asserts the final status code and response body. ```rust let mut res = post("http://example.org/post-redirect") .send("test body") .unwrap(); assert_eq!(res.status(), 200); let body = res.body_mut().read_to_string().unwrap(); assert_eq!(body, "success"); ``` -------------------------------- ### Partition Point Example Source: https://docs.rs/ureq/latest/ureq/unversioned/resolver/struct.ArrayVec.html Demonstrates finding the partition point in a slice based on a predicate. ```rust assert_eq!(i, 4); assert!(v[..i].iter().all(|&x| x < 5)); assert!(v[i..].iter().all(|&x| !(x < 5))); ``` ```rust let a = [2, 4, 8]; assert_eq!(a.partition_point(|x| x < &100), a.len()); let a: [i32; 0] = []; assert_eq!(a.partition_point(|x| x < &100), 0); ``` ```rust let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let num = 42; let idx = s.partition_point(|&x| x <= num); s.insert(idx, num); assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); ``` -------------------------------- ### Integration Test for HTTP GET Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Example test case demonstrating a GET request to a public URL and verifying response headers and body. ```rust #[test] fn connect_http_google() { init_test_log(); let agent = Agent::new_with_defaults(); let res = agent.get("http://www.google.com/").call().unwrap(); assert_eq!( "text/html;charset=ISO-8859-1", res.headers() .get("content-type") .unwrap() .to_str() .unwrap() .replace("; ", ";") ); assert_eq!(res.body().mime_type(), Some("text/html")); } ``` -------------------------------- ### Basic HTTP GET Request Source: https://docs.rs/ureq/latest/index.html Perform a simple GET request and read the response body as a string. Requires basic setup without an Agent. ```rust let body: String = ureq::get("http://example.com") .header("Example-Header", "header value") .call()?; .body_mut() .read_to_string()?; ``` -------------------------------- ### Connector Example Source: https://docs.rs/ureq/latest/ureq/unversioned/transport/trait.Connector.html Demonstrates how to create a custom connector chain using TcpConnector and RustlsConnector, and then use it to build a ureq Agent. ```APIDOC ## Example Usage ```rust use ureq::{Agent, config::Config}; use ureq::unversioned::transport::{Connector, TcpConnector, RustlsConnector}; use ureq::unversioned::resolver::DefaultResolver; // A connector chain that opens a TCP transport, then wraps it in a TLS. let connector = () // Start with a base connector (often empty tuple for no initial transport) .chain(TcpConnector::default()) .chain(RustlsConnector::default()); let config = Config::default(); let resolver = DefaultResolver::default(); // Creates an agent with a bespoke connector let agent = Agent::with_parts(config, connector, resolver); let mut res = agent.get("https://httpbin.org/get").call().unwrap(); let body = res.body_mut().read_to_string().unwrap(); ``` ``` -------------------------------- ### Middleware Example with SendBody Source: https://docs.rs/ureq/latest/ureq/struct.SendBody.html This example demonstrates how to use SendBody within a middleware to inspect and modify a request body before it's sent. It shows how to convert a SendBody into a reader, take a portion of its content, and then create a new SendBody from that portion. ```Rust use ureq::{SendBody, Body}; use ureq::middleware::MiddlewareNext; use ureq::http::{Request, Response, header::HeaderValue}; use std::io::Read; fn my_middleware(req: Request, next: MiddlewareNext) -> Result, ureq::Error> { // Take apart the request. let (parts, body) = req.into_parts(); // Take the first 100 bytes of the incoming send body. let mut reader = body.into_reader().take(100); // Create a new SendBody. let new_body = SendBody::from_reader(&mut reader); // Reconstitute the request. let req = Request::from_parts(parts, new_body); // set my bespoke header and continue the chain next.handle(req) } ``` -------------------------------- ### GET /agent Source: https://docs.rs/ureq/latest/ureq/fn.agent.html Initializes a new Agent instance with default configuration to manage state between HTTP requests. ```APIDOC ## GET /agent ### Description Creates a new Agent instance with default configuration. Agents are used to hold configuration and maintain state between multiple requests. ### Method GET ### Endpoint /agent ### Response #### Success Response (200) - **Agent** (Object) - A new Agent instance with default settings. ``` -------------------------------- ### Agent Initialization Source: https://docs.rs/ureq/latest/src/ureq/agent.rs.html Demonstrates how to create a new Agent instance with default settings or a custom configuration. ```APIDOC ## Agent Initialization ### Description Provides methods to create an `Agent` instance. An `Agent` can maintain state across multiple HTTP requests, such as cookies and connection pooling. ### Methods - `Agent::new_with_defaults()`: Creates an agent with default configurations for transport, resolver, and connection pooling. - `Agent::new_with_config(config: Config)`: Creates an agent using a provided `Config` object. ### Usage Example ```rust // Using default settings let mut agent = ureq::agent(); // Using a custom configuration (example assumes ConfigBuilder is used elsewhere) // let config = ureq::Config::builder()...build(); // let mut agent = ureq::agent_with_config(config); ``` ### Related - [`Config::builder()`]: For creating custom configurations. ``` -------------------------------- ### Send different content types Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Examples of sending form data, JSON, and multipart requests with appropriate headers. ```rust #[test] fn test_send_form_content_type() { init_test_log(); // These tests verify that the methods work correctly with the test infrastructure // The actual Content-Type verification happens at the transport level let form_data = [("key1", "value1"), ("key2", "value2")]; let mut res = post("http://httpbin.org/post") .header("x-verify-content-type", "application/x-www-form-urlencoded") .send_form(form_data) .unwrap(); let _txt = res.body_mut().read_to_string().unwrap(); } ``` ```rust #[test] #[cfg(feature = "json")] fn test_send_json_content_type() { use serde_json::json; init_test_log(); let data = json!({"key": "value"}); let mut res = post("http://httpbin.org/post") .header("x-verify-content-type", "application/json; charset=utf-8") .send_json(&data) .unwrap(); let _txt = res.body_mut().read_to_string().unwrap(); } ``` ```rust #[test] #[cfg(feature = "multipart")] fn test_send_multipart_content_type() { use crate::unversioned::multipart::Form; init_test_log(); let form = Form::new() .text("field1", "value1") .text("field2", "value2"); let mut res = post("http://httpbin.org/post") .header("x-verify-content-type", "multipart/form-data") .send(form) .unwrap(); let _txt = res.body_mut().read_to_string().unwrap(); } ``` -------------------------------- ### Get Mutable Output Buffer Source: https://docs.rs/ureq/latest/ureq/unversioned/transport/struct.LazyBuffers.html Provides mutable access to the output buffer for writing new data. Data is always written starting from index 0. ```rust fn output(&mut self) -> &mut [u8] ``` -------------------------------- ### Proxy Example: Builder Pattern Source: https://docs.rs/ureq/latest/src/ureq/proxy.rs.html Shows how to configure a proxy using the builder pattern, specifying protocol, host, port, credentials, and DNS resolution behavior. ```rust let proxy = Proxy::builder(ProxyProtocol::Socks5) .host("proxy.example.com") .port(1080) .username("user") .password("pass") .resolve_target(true) // Force local DNS resolution .build() .unwrap(); ``` -------------------------------- ### GET Request Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Initiates a GET request to a specified URI. ```APIDOC ## GET /{uri} ### Description Makes a GET request to the specified URI using a new Agent with default configuration. ### Method GET ### Endpoint /{uri} ### Parameters #### Path Parameters - **uri** (T) - Required - The URI to send the GET request to. Must be convertible to `Uri`. ### Response #### Success Response (200) - **RequestBuilder** (RequestBuilder) - A RequestBuilder configured for a GET request. ``` -------------------------------- ### fn take(self, limit: u64) -> Take Source: https://docs.rs/ureq/latest/ureq/struct.BodyReader.html Creates an adapter which will read at most `limit` bytes from it. ```APIDOC ## fn take(self, limit: u64) -> Take ### Description Creates an adapter that limits the number of bytes read from this `Read` instance. ### Method `take` ### Parameters - `limit` (`u64`): The maximum number of bytes to read. ### Returns - `Take`: An adapter that reads at most `limit` bytes. ``` -------------------------------- ### GET / Request Source: https://docs.rs/ureq/latest/ureq Perform a simple GET request using the ureq crate. ```APIDOC ## GET [URL] ### Description Performs a simple blocking GET request to the specified URL. ### Method GET ### Request Example ```rust let body: String = ureq::get("http://example.com") .header("Example-Header", "header value") .call()? .body_mut() .read_to_string()?; ``` ``` -------------------------------- ### Get TypeId for Any Trait Source: https://docs.rs/ureq/latest/ureq/tls/struct.ClientCert.html Gets the TypeId of the ClientCert. This is a blanket implementation for the Any trait. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Configure and use an Agent Source: https://docs.rs/ureq/latest/ureq/index.html Shows how to create an Agent with custom configuration for connection pooling and shared state across requests. ```rust use ureq::Agent; use std::time::Duration; let mut config = Agent::config_builder() .timeout_global(Some(Duration::from_secs(5))) .build(); let agent: Agent = config.into(); let body: String = agent.get("http://example.com/page") .call()? .body_mut() .read_to_string()?; // Reuses the connection from previous request. let response: String = agent.put("http://example.com/upload") .header("Authorization", "example-token") .send("some body data")? .body_mut() .read_to_string()?; ``` -------------------------------- ### Configure Request with Specific Agent and Customizations Source: https://docs.rs/ureq/latest/src/ureq/request_ext.rs.html This example shows how to use a specific agent and apply request-specific configurations on top before running the request. ```rust use ureq::{http, Agent, RequestExt, Error}; use std::time::Duration; let mut agent = Agent::config_builder() .timeout_global(Some(Duration::from_secs(30))) .build() .new_agent(); let request: Result, Error> = http::Request::builder() .method(http::Method::GET) .uri("http://foo.bar") .body(()) .unwrap() .with_agent(&agent) .configure() .http_status_as_error(false) .run(); ``` -------------------------------- ### method_ref Source: https://docs.rs/ureq/latest/ureq/struct.RequestBuilder.html Gets the HTTP Method for this request. Defaults to GET. Returns None if the builder has an error. ```APIDOC ## method_ref ### Description Gets the HTTP Method for this request. By default this is `GET`. If builder has error, returns None. ### Method `GET` (default) ### Parameters None ### Response - `Option<&Method>`: The HTTP Method of the request, or None if an error occurred. ### Example ```rust use ureq::http::Method; let req = ureq::get("http://httpbin.org/get"); assert_eq!(req.method_ref(), Some(&Method::GET)); let req = ureq::post("http://httpbin.org/post"); assert_eq!(req.method_ref(), Some(&Method::POST)); ``` ``` -------------------------------- ### Simple GET Request Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Performs a simple GET request to httpbin.org/get and reads the response body. ```rust #[test] fn simple_get() { init_test_log(); let mut res = get("http://httpbin.org/get").call().unwrap(); res.body_mut().read_to_string().unwrap(); } ``` -------------------------------- ### Creating and Using an Agent for Stateful Requests Source: https://docs.rs/ureq/latest/ureq/struct.Agent.html Demonstrates how to create an Agent and use it to perform stateful POST and GET requests, preserving cookies and other session information between calls. ```rust let mut agent = ureq::agent(); agent .post("http://example.com/post/login") .send(b"my password")?; let secret = agent .get("http://example.com/get/my-protected-page") .call()? .body_mut() .read_to_string()?; println!("Secret is: {}", secret); ``` -------------------------------- ### Get request function signature Source: https://docs.rs/ureq/latest/ureq/fn.get.html Defines the signature for making a GET request with a URI that implements TryFrom. ```rust pub fn get(uri: T) -> RequestBuilder where Uri: TryFrom, >::Error: Into, ``` -------------------------------- ### Connect to Google with Rustls and WebPKI Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Connects to google.com using Rustls and the WebPKI root certificate store. This example focuses on the connection itself. ```rust #[test] #[cfg(feature = "rustls")] fn connect_https_google_rustls_webpki() { init_test_log(); use crate::tls::{RootCerts, TlsConfig, TlsProvider}; use config::Config; let agent: Agent = Config::builder() .tls_config( TlsConfig::builder() .provider(TlsProvider::Rustls) .root_certs(RootCerts::WebPki) .build(), ) .build() .into(); agent.get("https://www.google.com/").call().unwrap(); } ``` -------------------------------- ### Perform a simple GET request Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html The most basic way to perform an HTTP GET request using ureq. ```rust let body: String = ureq::get("http://example.com") .header("Example-Header", "header value") .call()? .body_mut() .read_to_string()?; # Ok::<(), ureq::Error>(()) ``` -------------------------------- ### Connect to Google with Native TLS and WebPKI Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Connects to google.com using the native-tls provider and the WebPKI root certificate store. This example focuses on the connection itself. ```rust #[test] #[cfg(feature = "native-tls")] fn connect_https_google_native_tls_webpki() { init_test_log(); use crate::tls::{RootCerts, TlsConfig, TlsProvider}; use config::Config; let agent: Agent = Config::builder() .tls_config( TlsConfig::builder() .provider(TlsProvider::NativeTls) .root_certs(RootCerts::WebPki) .build(), ) .build() .into(); agent.get("https://www.google.com/").call().unwrap(); } ``` -------------------------------- ### Get Request URI Source: https://docs.rs/ureq/latest/ureq/struct.RequestBuilder.html Use uri_ref to get a reference to the URI for the current request. The default URI is '/'. ```rust let req = ureq::get("http://httpbin.org/get"); assert_eq!(req.uri_ref().unwrap(), "http://httpbin.org/get"); ``` -------------------------------- ### Get HTTP Method - RequestBuilder Source: https://docs.rs/ureq/latest/ureq/struct.RequestBuilder.html Retrieves the HTTP Method of the request. Defaults to GET. Returns None if the builder has an error. ```rust use ureq::http::Method; let req = ureq::get("http://httpbin.org/get"); assert_eq!(req.method_ref(),Some(&Method::GET)); let req = ureq::post("http://httpbin.org/post"); assert_eq!(req.method_ref(),Some(&Method::POST)); ``` -------------------------------- ### Utilities and Configuration Source: https://docs.rs/ureq/latest/ureq Documentation for utility structs, enums, and traits. ```APIDOC ## Cookie ### Description Representation of an HTTP cookie. ``` ```APIDOC ## CookieJar ### Description Collection of cookies. ``` ```APIDOC ## Proxy ### Description Proxy server settings ``` ```APIDOC ## ProxyBuilder ### Description Builder for configuring a proxy. ``` ```APIDOC ## ProxyProtocol ### Description Proxy protocol ``` ```APIDOC ## Timeout ### Description The various timeouts. ``` ```APIDOC ## Error ### Description Errors from ureq. ``` -------------------------------- ### Perform a simple GET request Source: https://docs.rs/ureq/latest/ureq/index.html Demonstrates the most basic usage of ureq to perform a GET request and read the response body as a string. ```rust let body: String = ureq::get("http://example.com") .header("Example-Header", "header value") .call()? .body_mut() .read_to_string()?; ``` -------------------------------- ### Proxy Builder Basic Configuration Source: https://docs.rs/ureq/latest/src/ureq/proxy.rs.html Demonstrates using the `Proxy::builder` to configure a SOCKS4 proxy with host, port, and resolve target settings. ```rust let proxy = Proxy::builder(ProxyProtocol::Socks4) .host("my-proxy.com") .port(5551) .resolve_target(false) .build() .unwrap(); assert_eq!(proxy.protocol(), ProxyProtocol::Socks4); assert_eq!(proxy.uri(), "SOCKS4://my-proxy.com:5551/"); assert_eq!(proxy.host(), "my-proxy.com"); assert_eq!(proxy.port(), 5551); assert_eq!(proxy.username(), None); assert_eq!(proxy.password(), None); assert_eq!(proxy.is_from_env(), false); assert_eq!(proxy.resolve_target(), false); ``` -------------------------------- ### Example: Using aws-lc-rs with Rustls Source: https://docs.rs/ureq/latest/src/ureq/tls/mod.rs.html Demonstrates how to configure an Agent with a custom Rustls crypto provider (aws-lc-rs) by disabling default features and enabling specific ones in Cargo.toml. ```text ureq = { version = "3", default-features = false, features = ["rustls-no-provider"] } rustls = { version = "0.23", features = ["aws-lc-rs"] } ``` ```rust use std::sync::Arc; use ureq::{Agent}; use ureq::tls::{TlsConfig, TlsProvider}; use rustls::crypto; let crypto = Arc::new(crypto::aws_lc_rs::default_provider()); let agent = Agent::config_builder() .tls_config( TlsConfig::builder() .provider(TlsProvider::Rustls) // requires rustls or rustls-no-provider feature .unversioned_rustls_crypto_provider(crypto) .build() ) .build() .new_agent(); ``` -------------------------------- ### Send GET Request and Call - ureq Source: https://docs.rs/ureq/latest/src/ureq/request.rs.html Sends a GET request and blocks until a response is received. It does not send Content-Length or Transfer-Encoding headers. ```rust let res = ureq::get("http://httpbin.org/get") .call()?; # Ok::<_, ureq::Error>(()) ``` -------------------------------- ### GET Request with Query Parameter (No Slash) Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Performs a GET request to httpbin.org with a query parameter, demonstrating a URL without a trailing slash. ```rust #[test] fn query_no_slash() { init_test_log(); let mut res = get("http://httpbin.org?query=foo").call().unwrap(); ``` -------------------------------- ### PROPFIND with Body Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Demonstrates making a PROPFIND request with a request body, which is non-standard but supported when allowed. Requires the '_test' feature. ```rust #[test] #[cfg(feature = "_test")] fn propfind_with_body() { init_test_log(); // https://github.com/algesten/ureq/issues/1034 let request = http::Request::builder() .method("PROPFIND") .uri("https://www.google.com/") .body("Some really cool body") .unwrap(); let _ = Agent::config_builder() .allow_non_standard_methods(true) .build() .new_agent() .run(request) .unwrap(); } ``` -------------------------------- ### Connect to Google with Native TLS (Simple) Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Connects to google.com using the native-tls provider. Asserts the content type and MIME type, and reads the response body. ```rust #[test] #[cfg(feature = "native-tls")] fn connect_https_google_native_tls_simple() { init_test_log(); use config::Config; use crate::tls::{TlsConfig, TlsProvider}; let agent: Agent = Config::builder() .tls_config( TlsConfig::builder() .provider(TlsProvider::NativeTls) .build(), ) .build() .into(); let mut res = agent.get("https://www.google.com/").call().unwrap(); assert_eq!( "text/html;charset=ISO-8859-1", res.headers() .get("content-type") .unwrap() .to_str() .unwrap() .replace("; ", ";") ); assert_eq!(res.body().mime_type(), Some("text/html")); res.body_mut().read_to_string().unwrap(); } ``` -------------------------------- ### Getting Current Instant Source: https://docs.rs/ureq/latest/src/ureq/timings.rs.html Returns the current `Instant` based on the `CurrentTime` source configured for `CallTimings`. This is a convenience method for directly getting the current time. ```rust pub(crate) fn now(&self) -> Instant { self.current_time.now() } ``` -------------------------------- ### Create a custom connector chain Source: https://docs.rs/ureq/latest/src/ureq/unversioned/transport/mod.rs.html Demonstrates how to build a connector chain using TcpConnector and RustlsConnector, then applying it to a ureq Agent. ```rust # #[cfg(all(feature = "rustls", not(feature = "_test")))] { use ureq::{Agent, config::Config}; // These types are not covered by the promises of semver (yet) use ureq::unversioned::transport::{Connector, TcpConnector, RustlsConnector}; use ureq::unversioned::resolver::DefaultResolver; // A connector chain that opens a TCP transport, then wraps it in a TLS. let connector = () .chain(TcpConnector::default()) .chain(RustlsConnector::default()); let config = Config::default(); let resolver = DefaultResolver::default(); // Creates an agent with a bespoke connector let agent = Agent::with_parts(config, connector, resolver); let mut res = agent.get("https://httpbin.org/get").call().unwrap(); let body = res.body_mut().read_to_string().unwrap(); # } ``` -------------------------------- ### Part Configuration Methods Source: https://docs.rs/ureq/latest/src/ureq/multipart.rs.html Methods for configuring metadata on a Part instance. ```rust pub fn file_name(mut self, name: &str) -> Self { self.meta.file_name = Some(name.to_string()); self } ``` ```rust pub fn mime_str(mut self, mime: &str) -> Result { let mime_type = mime.parse().map_err(Error::InvalidMimeType)?; self.meta.mime = Some(mime_type); Ok(self) } ``` -------------------------------- ### Handle GET Request with JSON Response Source: https://docs.rs/ureq/latest/src/ureq/unversioned/transport/test.rs.html Responds to GET requests with a 200 OK status and application/json content type. Writes predefined JSON data. ```rust write!( w, "HTTP/1.1 200 OK\r\n\ Content-Type: application/json\r\n\ Content-Length: {}\r\n\ \r\n", HTTPBIN_JSON.len() )?; w.write_all(HTTPBIN_JSON.as_bytes()) ``` -------------------------------- ### Get Unsafe Mutable Pointer to Slice Buffer Source: https://docs.rs/ureq/latest/ureq/unversioned/resolver/struct.ArrayVec.html Get an unsafe mutable pointer to the slice's buffer with `as_mut_ptr`. Be cautious about slice lifetime and potential reallocations invalidating the pointer. ```rust let x = &mut [1, 2, 4]; let x_ptr = x.as_mut_ptr(); unsafe { for i in 0..x.len() { *x_ptr.add(i) += 2; } } assert_eq!(x, &[3, 4, 6]); ``` -------------------------------- ### HTTP Connect Proxy Configuration Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Demonstrates configuring an agent to use an HTTP CONNECT proxy. Requires the '_test' feature. ```rust #[test] #[cfg(feature = "_test")] fn http_connect_proxy() { init_test_log(); let proxy = Proxy::new("http://my_proxy:1234/connect-proxy").unwrap(); let agent = Agent::config_builder() .proxy(Some(proxy)) .build() .new_agent(); let mut res = agent.get("http://httpbin.org/get").call().unwrap(); res.body_mut().read_to_string().unwrap(); } ``` -------------------------------- ### uri_ref Source: https://docs.rs/ureq/latest/ureq/struct.RequestBuilder.html Get the URI for this request. By default this is `/`. ```APIDOC ## uri_ref ### Description Get the URI for this request. By default this is `/`. ### Method Signature `pub fn uri_ref(&self) -> Option<&Uri>` ### Returns An `Option` containing a reference to the request's `Uri` if set, otherwise `None`. ### Example ```rust let req = ureq::get("http://httpbin.org/get"); assert_eq!(req.uri_ref().unwrap(), "http://httpbin.org/get"); ``` ``` -------------------------------- ### Agent Usage Example Source: https://docs.rs/ureq/latest/src/ureq/agent.rs.html Illustrates a typical workflow using an Agent to make sequential HTTP requests, demonstrating state persistence (like cookies). ```APIDOC ## Agent Usage Example ### Description This example shows how an `Agent` can be used to make a series of requests, where state (like cookies) is maintained between them. The `Agent` itself is cloneable, allowing shared state across threads. ### Example ```rust // Create an agent let mut agent = ureq::agent(); // Make a POST request, potentially sending login credentials agent .post("http://example.com/post/login") .send(b"username=test&password=password")?; // Make a subsequent GET request, which might use cookies set by the previous request let response = agent .get("http://example.com/get/my-protected-page") .call()?; let secret_content = response.into_string()?; println!("Secret content: {}", secret_content); # Ok::<(), ureq::Error>(()) ``` ### Key Concepts - **State Persistence**: The `Agent` holds state (e.g., cookies) across requests. - **Cloning**: Agents can be cloned (`agent.clone()`) to share the underlying connection pool and state across threads. - **Request Lifecycle**: The agent is borrowed during request sending and response header reception. The response body can be processed independently. ``` -------------------------------- ### GET /config Source: https://docs.rs/ureq/latest/src/ureq/agent.rs.html Retrieves the configuration for the agent. ```APIDOC ## GET /config ### Description Retrieves the current configuration associated with this agent instance. ### Method GET ### Endpoint /config ### Response #### Success Response (200) - **Config** - The configuration object for the agent. ``` -------------------------------- ### Agent Configuration and Initialization Source: https://docs.rs/ureq/latest/src/ureq/config.rs.html Methods for creating a new agent from a configuration and accessing various configuration settings. ```APIDOC ## Config::builder ### Description Creates a builder to generate a bespoke configuration with default values already set. ## Config::new_agent ### Description Creates a new agent by cloning the current configuration. Cloning the config does not incur heap allocations. ## Config::http_status_as_error ### Description Returns whether to treat 4xx and 5xx HTTP status codes as errors. Defaults to true. ## Config::https_only ### Description Returns whether to limit requests (including redirects) to https only. Defaults to false. ## Config::max_redirects ### Description Returns the maximum number of redirects to follow before giving up. Defaults to 10. ``` -------------------------------- ### Instantiate PoolKey and Test Scheme Handling Source: https://docs.rs/ureq/latest/src/ureq/pool.rs.html Demonstrates the creation of a PoolKey and a test case ensuring that unrecognized URI schemes do not cause a panic. ```rust PoolKey::new(details.uri, details.config.proxy()) } } #[cfg(all(test, feature = "_test"))] mod test { use super::*; #[test] fn poolkey_new() { // Test that PoolKey::new() does not panic on unrecognized schemes. PoolKey::new(&Uri::from_static("zzz://example.com"), None); } } ``` -------------------------------- ### version_ref Source: https://docs.rs/ureq/latest/ureq/struct.RequestBuilder.html Get the HTTP version for this request. By default this is HTTP/1.1. ```APIDOC ## version_ref ### Description Get the HTTP version for this request. By default this is HTTP/1.1. ### Method Signature `pub fn version_ref(&self) -> Option<&Version>` ### Returns An `Option` containing a reference to the request's `Version` if set, otherwise `None`. ### Example ```rust use ureq::http::Version; let req = ureq::get("http://httpbin.org/get"); assert_eq!(req.version_ref().unwrap(), &Version::HTTP_11); ``` ``` -------------------------------- ### ureq RequestExt: Using with_default_agent and Configure Source: https://docs.rs/ureq/latest/ureq/trait.RequestExt.html Demonstrates using `with_default_agent` to leverage the globally configured default agent for a request, followed by `configure()` to apply specific settings like disabling HTTP status errors. This is a convenient way to make requests with default settings and custom overrides. ```rust use ureq::{http, RequestExt, Error}; let request: Result, Error> = http::Request::builder() .method(http::Method::GET) .uri("http://foo.bar") .body(()) .unwrap() .with_default_agent() .configure() .http_status_as_error(false) .run(); ``` -------------------------------- ### Get PrivateKey kind Source: https://docs.rs/ureq/latest/ureq/tls/struct.PrivateKey.html Returns the kind of the private key. ```rust pub fn kind(&self) -> KeyKind ``` -------------------------------- ### Configure an Agent Source: https://docs.rs/ureq/latest/src/ureq/config.rs.html Create an Agent with custom global settings using a configuration builder. ```rust use ureq::Agent; use std::time::Duration; let config = Agent::config_builder() .timeout_global(Some(Duration::from_secs(10))) .https_only(true) .build(); let agent = Agent::new_with_config(config); ``` -------------------------------- ### Get Request URI Source: https://docs.rs/ureq/latest/src/ureq/request.rs.html Retrieves the current URI of the request. ```APIDOC ## GET /api/resource ### Description Retrieves the URI currently set for the request. ### Method GET ### Endpoint /api/resource ### Parameters None ### Request Example ```rust let req = ureq::get("http://httpbin.org/get"); assert_eq!(req.uri_ref().unwrap(), "http://httpbin.org/get"); ``` ### Response #### Success Response (200) - **uri** (string) - The current URI of the request. #### Response Example ```json { "uri": "http://httpbin.org/get" } ``` ``` -------------------------------- ### Create Proxy Configuration via Builder Source: https://docs.rs/ureq/latest/src/ureq/proxy.rs.html Initializes a proxy configuration using the ProxyBuilder pattern. ```rust pub fn builder(p: ProxyProtocol) -> ProxyBuilder { ProxyBuilder { protocol: p, host: None, port: None, username: None, password: None, resolve_target: p.default_resolve_target(), no_proxy: None, } } ``` -------------------------------- ### Basic Authentication from URI Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Demonstrates how to include username and password directly in the URI for basic authentication and verifies the authentication header in the response. ```rust let mut res = get("https://martin:secret@httpbin.org/get").call().unwrap(); let body = res.body_mut().read_to_string().unwrap(); assert!(body.contains("Basic bWFydGluOnNlY3JldA==")); ``` -------------------------------- ### GET /cookie_jar_lock Source: https://docs.rs/ureq/latest/src/ureq/agent.rs.html Accesses the shared cookie jar for the agent. ```APIDOC ## GET /cookie_jar_lock ### Description Accesses the shared cookie jar to persist or manipulate cookies. The jar is shared between all clones of the same Agent. ### Method GET ### Endpoint /cookie_jar_lock ### Response #### Success Response (200) - **CookieJar** - A lockable reference to the shared cookie jar. ``` -------------------------------- ### fn type_id(&self) -> TypeId Source: https://docs.rs/ureq/latest/ureq/unversioned/transport/struct.TransportAdapter.html Gets the TypeId of the borrowed object. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. This method is part of the blanket implementation of `Any` for `T`. ### Parameters - `&self`: An immutable reference to the object. ### Returns - `TypeId`: The unique identifier for the type of `self`. ``` -------------------------------- ### Agent Level Config Example Source: https://docs.rs/ureq/latest/ureq/config/struct.Config.html Builds a global agent configuration with a global timeout and enforces HTTPS. This configuration is then used to create a new agent. ```rust use ureq::Agent; use std::time::Duration; let config = Agent::config_builder() .timeout_global(Some(Duration::from_secs(10))) .https_only(true) .build(); let agent = Agent::new_with_config(config); ``` -------------------------------- ### iter Source: https://docs.rs/ureq/latest/ureq/unversioned/resolver/struct.ArrayVec.html Returns an iterator over the slice, yielding elements from start to end. ```APIDOC ## pub fn iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Method `fn iter` ### Returns An iterator over the slice. ### Examples ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ``` -------------------------------- ### Get Client Private Key Source: https://docs.rs/ureq/latest/src/ureq/tls/mod.rs.html Retrieves the private key of the client certificate. ```rust pub fn private_key(&self) -> &PrivateKey<'static> { &self.0.1 } ``` -------------------------------- ### Handling large responses with limit() Source: https://docs.rs/ureq/latest/ureq/struct.BodyWithConfig.html Demonstrates how to use `with_config().limit()` to download large files without exhausting memory. ```APIDOC ## Download a large file ```rust // Download a 50MB file let large_data = ureq::get("http://httpbin.org/bytes/200000000") .call()? .body_mut() .with_config() .limit(50 * 1024 * 1024) // 50MB .read_to_vec()?; ``` ``` -------------------------------- ### Create a New Agent Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Initializes an Agent with default configuration settings for managing request state. ```rust pub fn agent() -> Agent { Agent::new_with_defaults() } ``` -------------------------------- ### Get Client Certificate Chain Source: https://docs.rs/ureq/latest/src/ureq/tls/mod.rs.html Retrieves the certificate chain of the client certificate. ```rust pub fn certs(&self) -> &[Certificate<'static>] { &self.0.0 } ``` -------------------------------- ### Custom Connector Chain Example Source: https://docs.rs/ureq/latest/ureq/unversioned/transport/trait.Connector.html Demonstrates creating a custom connector chain that first establishes a TCP connection and then wraps it with TLS using RustlsConnector. This agent can then be used for making HTTP requests. ```rust use ureq::{Agent, config::Config}; // These types are not covered by the promises of semver (yet) use ureq::unversioned::transport::{Connector, TcpConnector, RustlsConnector}; use ureq::unversioned::resolver::DefaultResolver; // A connector chain that opens a TCP transport, then wraps it in a TLS. let connector = () .chain(TcpConnector::default()) .chain(RustlsConnector::default()); let config = Config::default(); let resolver = DefaultResolver::default(); // Creates an agent with a bespoke connector let agent = Agent::with_parts(config, connector, resolver); let mut res = agent.get("https://httpbin.org/get").call().unwrap(); let body = res.body_mut().read_to_string().unwrap(); ``` -------------------------------- ### ArrayVec Iterator Example Source: https://docs.rs/ureq/latest/ureq/unversioned/resolver/struct.ArrayVec.html Demonstrates the iteration over an ArrayVec, yielding Range structs. ```rust assert_eq!(iter.next(), Some(Range { start: 0, end: 0 })); assert_eq!(iter.next(), Some(Range { start: 1, end: 3 })); assert_eq!(iter.next(), Some(Range { start: 4, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 5, end: 6 })); ``` -------------------------------- ### Basic File Upload with Form Source: https://docs.rs/ureq/latest/ureq/unversioned/multipart/struct.Form.html Demonstrates how to create a new Form, add a text field, and upload a file using its path. The Content-Type header is automatically set when sending. ```rust use ureq::unversioned::multipart::Form; let form = Form::new() .text("description", "My uploaded file") .file("upload", "path/to/file.txt")?; // Send the form as part of a POST request let response = ureq::post("http://httpbin.org/post") .send(form)?; ``` -------------------------------- ### extensions_ref Source: https://docs.rs/ureq/latest/ureq/struct.RequestBuilder.html Get a reference to the extensions for this request builder. If the builder has an error, this returns `None`. ```APIDOC ## extensions_ref ### Description Get a reference to the extensions for this request builder. If the builder has an error, this returns `None`. ### Method Signature `pub fn extensions_ref(&self) -> Option<&Extensions>` ### Returns An `Option` containing a reference to the `Extensions` map if the builder is valid, otherwise `None`. ### Example ```rust let req = ureq::get("http://httpbin.org/get") .extension("My Extension").extension(5u32); let extensions = req.extensions_ref().unwrap(); assert_eq!(extensions.get::<&'static str>(), Some(&"My Extension")); assert_eq!(extensions.get::(), Some(&5u32)); ``` ``` -------------------------------- ### Get Total Nanoseconds from Duration Source: https://docs.rs/ureq/latest/ureq/unversioned/transport/time/enum.Duration.html Converts a Duration to the total number of nanoseconds it represents. ```rust use std::time::Duration; let duration = Duration::new(5, 730_023_852); assert_eq!(duration.as_nanos(), 5_730_023_852); ``` -------------------------------- ### Configure Agent Buffer and Connection Settings Source: https://docs.rs/ureq/latest/src/ureq/config.rs.html Methods for setting response header sizes, buffer sizes, and connection pool limits. ```rust pub fn max_response_header_size(mut self, v: usize) -> Self { self.config().max_response_header_size = v; self } /// Default size of the input buffer /// /// The default connectors use this setting. /// /// Defaults to 128kb. pub fn input_buffer_size(mut self, v: usize) -> Self { self.config().input_buffer_size = v; self } /// Default size of the output buffer. /// /// The default connectors use this setting. /// /// Defaults to 128kb. pub fn output_buffer_size(mut self, v: usize) -> Self { self.config().output_buffer_size = v; self } /// Max number of idle pooled connections overall. /// /// This setting has no effect when used per-request. /// /// Defaults to 10 pub fn max_idle_connections(mut self, v: usize) -> Self { self.config().max_idle_connections = v; self } /// Max number of idle pooled connections per host/port combo. /// /// This setting has no effect when used per-request. /// /// Defaults to 3 pub fn max_idle_connections_per_host(mut self, v: usize) -> Self { self.config().max_idle_connections_per_host = v; self } /// Max duration to keep an idle connection in the pool /// /// This can also be configured per-request to be shorter than the pool. /// For example: if the pool is configured to 15 seconds and we have a /// connection with an age of 10 seconds, a request setting this config /// property to 3 seconds, would ignore the pooled connection (but still /// leave it in the pool). /// /// Defaults to 15 seconds pub fn max_idle_age(mut self, v: Duration) -> Self { self.config().max_idle_age = v; self } ``` -------------------------------- ### Get TlsProvider Source: https://docs.rs/ureq/latest/ureq/tls/struct.TlsConfig.html Retrieves the TlsProvider used for the TLS configuration. Defaults to TlsProvider::Rustls. ```rust pub fn provider(&self) -> TlsProvider ``` -------------------------------- ### Create Proxy from URI Source: https://docs.rs/ureq/latest/ureq/struct.Proxy.html Creates a proxy configuration by parsing a URI string. Requires the URI to be valid. ```rust use ureq::{Proxy, ProxyProtocol}; // Create a proxy from a URI string let proxy = Proxy::new("http://localhost:8080").unwrap(); ``` -------------------------------- ### Get HTTP Version of Request Source: https://docs.rs/ureq/latest/src/ureq/request.rs.html Retrieves the HTTP version of a request. Defaults to HTTP/1.1. ```rust use ureq::http::Version; let req = ureq::get("http://httpbin.org/get"); assert_eq!(req.version_ref().unwrap(), &Version::HTTP_11); ``` -------------------------------- ### Get the size of a SendBody Source: https://docs.rs/ureq/latest/src/ureq/send_body.rs.html Retrieves the size of the SendBody if it's available and successfully determined. ```rust pub(crate) fn size(&self) -> Option { self.size.as_ref().and_then(|r| r.as_ref().ok()).copied() } ``` -------------------------------- ### Perform a HEAD request Source: https://docs.rs/ureq/latest/src/ureq/lib.rs.html Demonstrates executing a simple HEAD request using the ureq client. ```rust #[test] fn simple_head() { init_test_log(); let mut res = head("http://httpbin.org/get").call().unwrap(); res.body_mut().read_to_string().unwrap(); } ``` -------------------------------- ### starts_with: Check for prefix Source: https://docs.rs/ureq/latest/ureq/unversioned/resolver/struct.ArrayVec.html Verifies if a slice begins with a specified sequence of elements. An empty needle always returns true. ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` ```rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` -------------------------------- ### Split Off Tail Elements Source: https://docs.rs/ureq/latest/ureq/unversioned/resolver/struct.ArrayVec.html Splits a slice to remove and return elements starting from the third. ```rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut tail = slice.split_off(2..).unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(tail, &['c', 'd']); ``` -------------------------------- ### Running Raw HTTP Requests with Agent Source: https://docs.rs/ureq/latest/ureq/struct.Agent.html Shows how to execute a raw `http::Request` directly using an agent. Ensure the agent and request are compatible. ```rust use ureq::{http, Agent}; let agent: Agent = Agent::new_with_defaults(); let mut request = http::Request::get("http://httpbin.org/get") .body(())?; let body = agent.run(request)? .body_mut() .read_to_string()?; ``` -------------------------------- ### Get Slice Length Source: https://docs.rs/ureq/latest/ureq/unversioned/resolver/struct.ArrayVec.html Returns the number of elements in the slice. This is a common operation for array-like structures. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### ureq RequestExt: Customizing Request with Agent and Configure Source: https://docs.rs/ureq/latest/ureq/trait.RequestExt.html Shows how to use `with_agent` to specify a custom agent and then chain `configure()` to apply request-specific settings like `http_status_as_error(false)`. This allows fine-grained control over individual requests. ```rust use ureq::{http, Agent, RequestExt, Error}; use std::time::Duration; let mut agent = Agent::config_builder() .timeout_global(Some(Duration::from_secs(30))) .build() .new_agent(); let request: Result, Error> = http::Request::builder() .method(http::Method::GET) .uri("http://foo.bar") .body(()) .unwrap() .with_agent(&agent) .configure() .http_status_as_error(false) .run(); ```