### Basic GET Request Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Demonstrates how to perform a simple GET request. No special setup is required beyond importing the necessary types. ```rust use minreq::get; fn main() { let response = get("https://httpbin.org/get").send().unwrap(); assert_eq!(response.status_code(), 200); } ``` -------------------------------- ### Version Pinning Examples Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md Examples of how to pin the minreq version in Cargo.toml to control update behavior. ```toml # Lock to 3.0.x minreq = "~3.0" ``` ```toml # Allow patch updates only minreq = "3.0.*" ``` ```toml # Specific version minreq = "=3.0.0" ``` -------------------------------- ### Cargo.toml Full Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md A comprehensive `Cargo.toml` example including common features like HTTPS and JSON support. ```toml [dependencies] minreq = { version = "0.1", features = ["rustls-tls", "json-using-serde"], } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" ``` -------------------------------- ### Sending Requests with Different Methods Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/request-methods.md Demonstrates how to send requests using the convenience functions for GET, POST, PUT, and DELETE methods. Includes examples with request bodies and JSON payloads. ```rust minreq::get("http://example.com").send()?; minreq::post("http://example.com").with_body("data").send()?; minreq::put("http://example.com/1").with_json(&data)?.send()?; minreq::delete("http://example.com/1").send()?; ``` -------------------------------- ### Cargo.toml Minimal Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Shows the minimal `Cargo.toml` configuration to include Minreq as a dependency. ```toml [dependencies] minreq = "0.1" ``` -------------------------------- ### Using a Proxy Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Configures the request to use an HTTP proxy. Requires the `proxy` feature to be enabled. ```rust use minreq::get; fn main() { // Example using a proxy with basic authentication let proxy_url = "http://user:password@proxy.example.com:8080"; let response = get("https://www.example.com") .with_proxy(proxy_url) .send() .unwrap(); assert_eq!(response.status_code(), 200); } ``` -------------------------------- ### Incremental Building Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Shows how to build a request incrementally by chaining builder methods. This allows for more complex request configurations. ```rust use minreq::get; fn main() { let mut request_builder = get("https://httpbin.org/get"); request_builder .with_header("X-Custom", "Value") .with_param("query", "test"); let response = request_builder.send().unwrap(); assert_eq!(response.status_code(), 200); // println!("{}", response.as_str().unwrap()); } ``` -------------------------------- ### HTTPS GET Request with System Roots Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md This example shows a basic HTTPS GET request. When using the 'https-rustls-probe' feature, it automatically attempts to use system root certificates if available. ```rust let response = minreq::get("https://api.example.com").send()?; // Automatically uses system roots if available ``` -------------------------------- ### URL Type Usage Examples Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/types.md Shows examples of using the URL type alias with different URL formats for making requests. ```rust minreq::get("http://example.com"); minreq::post("https://api.example.com/users"); minreq::get("http://example.com:3000/api?page=1"); ``` -------------------------------- ### Query Parameters Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Shows how to append query parameters to a URL. This is useful for filtering or specifying options in the request. ```rust use minreq::get; fn main() { let response = get("https://httpbin.org/get") .with_param("name", "value") .with_param("id", "123") .send() .unwrap(); assert_eq!(response.status_code(), 200); // The response body will show the parameters received // println!("{}", response.as_str().unwrap()); } ``` -------------------------------- ### Make a Basic GET Request Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/README.md Send a GET request to a URL and print the response body as a string. Requires the `send()` method and `as_str()` for response body access. ```rust let response = minreq::get("http://example.com").send()?; println!("{}", response.as_str()?); ``` -------------------------------- ### Binary Response Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Demonstrates how to retrieve the response body as raw bytes. Useful for non-textual content like images or files. ```rust use minreq::get; fn main() { let response = get("https://httpbin.org/image/png").send().unwrap(); assert_eq!(response.status_code(), 200); let body_bytes = response.as_bytes().unwrap(); println!("Received {} bytes.", body_bytes.len()); // You can also get an owned Vec using into_bytes() // let owned_bytes: Vec = response.into_bytes().unwrap(); } ``` -------------------------------- ### HTTP Methods Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Demonstrates using different HTTP methods like POST, PUT, DELETE, etc. Minreq provides convenience functions for common methods. ```rust use minreq::{get, post, put, delete}; fn main() { // GET example let get_response = get("https://httpbin.org/get").send().unwrap(); assert_eq!(get_response.status_code(), 200); // POST example let post_response = post("https://httpbin.org/post").send().unwrap(); assert_eq!(post_response.status_code(), 200); // PUT example let put_response = put("https://httpbin.org/put").send().unwrap(); assert_eq!(put_response.status_code(), 200); // DELETE example let delete_response = delete("https://httpbin.org/delete").send().unwrap(); assert_eq!(delete_response.status_code(), 200); } ``` -------------------------------- ### Retry Pattern Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Illustrates a common pattern for retrying a request if it fails, for example, due to transient network issues. ```rust use minreq::get; use std::time::Duration; fn main() { let max_retries = 3; let mut attempt = 0; loop { match get("https://httpbin.org/delay/1").send() { Ok(response) => { println!("Success on attempt {}: Status {}", attempt + 1, response.status_code()); break; // Exit loop on success } Err(e) => { eprintln!("Attempt {} failed: {}", attempt + 1, e); attempt += 1; if attempt >= max_retries { eprintln!("Max retries reached. Aborting."); break; // Exit loop after max retries } // Wait before retrying std::thread::sleep(Duration::from_secs(1)); } } } } ``` -------------------------------- ### Custom Headers Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Demonstrates adding custom headers to a request. Use `with_header` for a single header or `with_headers` for multiple. ```rust use minreq::get; fn main() { let response = get("https://httpbin.org/headers") .with_header("X-Custom-Header", "MyValue") .with_header("User-Agent", "MinreqExample/1.0") .send() .unwrap(); assert_eq!(response.status_code(), 200); // The response body will contain the headers sent // println!("{}", response.as_str().unwrap()); } ``` -------------------------------- ### Minimal minreq Dependency Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/README.md Add minreq to your project for HTTP-only requests. This is the most basic setup. ```toml [dependencies] minreq = "3.0" ``` -------------------------------- ### Different Response Types Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Demonstrates handling different types of responses, such as text, JSON, or binary data, based on the request's needs. ```rust use minreq::get; fn main() { // Example 1: Get response as string let text_response = get("https://httpbin.org/html").send().unwrap(); let html_content = text_response.as_str().unwrap(); println!("HTML content length: {}", html_content.len()); // Example 2: Get response as JSON (requires json-using-serde feature) // let json_response = get("https://httpbin.org/json").send().unwrap(); // let data: serde_json::Value = json_response.json().unwrap(); // println!("JSON data: {:?}", data); // Example 3: Get response as bytes let image_response = get("https://httpbin.org/image/png").send().unwrap(); let image_bytes = image_response.as_bytes().unwrap(); println!("Image bytes length: {}", image_bytes.len()); } ``` -------------------------------- ### Cargo.toml JSON Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Specifies `Cargo.toml` dependencies to enable JSON support in Minreq, which relies on the `serde` and `serde_json` crates. ```toml [dependencies] minreq = { version = "0.1", features = ["json-using-serde"], } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" ``` -------------------------------- ### Basic GET Request Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/quickstart.md Send a simple GET request to a URL and print the status code and response body. ```rust fn main() -> Result<(), Box> { let response = minreq::get("http://example.com").send()?; println!("Status: {}", response.status_code); println!("Body: {}", response.as_str()?); Ok(()) } ``` -------------------------------- ### Multi-Address DNS Resolution Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/connection-and-tls.md Demonstrates how Minreq attempts to connect to multiple IP addresses resolved from a hostname, stopping on the first successful connection. This is handled automatically by the library. ```rust // example.com might resolve to multiple IPs minreq::get("http://example.com").send()?; // Library tries each IP until one succeeds ``` -------------------------------- ### HTTP Methods in Rust Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/quickstart.md Demonstrates how to perform common HTTP requests like GET, POST, PUT, DELETE, PATCH, and HEAD using the minreq library. Also shows how to make custom HTTP method requests. ```rust fn main() -> Result<(), Box> { // GET minreq::get("http://example.com/resource").send()?; // POST minreq::post("http://example.com/resource") .with_body("data") .send()?; // PUT minreq::put("http://example.com/resource/1") .with_body("data") .send()?; // DELETE minreq::delete("http://example.com/resource/1").send()?; // PATCH minreq::patch("http://example.com/resource/1") .with_body("data") .send()?; // HEAD minreq::head("http://example.com/resource").send()?; // Custom method minreq::Request::new( minreq::Method::Custom("CUSTOM".to_string()), "http://example.com" ).send()?; Ok(()) } ``` -------------------------------- ### Cargo.toml HTTPS Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Configures `Cargo.toml` to enable HTTPS support for Minreq. This typically involves enabling specific features. ```toml [dependencies] minreq = { version = "0.1", features = ["rustls-tls"], # or "native-tls" } ``` -------------------------------- ### Create a New HTTP Request Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/request-methods.md Use `Request::new` to initialize a new HTTP request with a specified method and URL. This is the starting point for building more complex requests. ```rust pub fn new>(method: Method, url: T) -> Request ``` ```rust let request = minreq::Request::new( minreq::Method::Get, "http://example.com" ); ``` -------------------------------- ### Example HTTP CONNECT Exchange with Proxy Authentication Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/proxy.md Illustrates a typical client-to-proxy communication using the HTTP CONNECT method for establishing a tunnel, including the necessary Proxy-Authorization header for authentication. ```http Client: CONNECT example.com:443 HTTP/1.1 Proxy-Authorization: Basic dXNlcjpwYXNz Proxy: HTTP/1.1 200 Connection Established Client: (now sends TLS handshake / HTTP request through tunnel) ``` -------------------------------- ### Basic HTTPS GET Request Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md This snippet demonstrates a basic GET request to an HTTPS URL using minreq. Ensure the appropriate HTTPS feature (e.g., 'https') is enabled in your Cargo.toml. ```rust let response = minreq::get("https://api.example.com").send()?; ``` -------------------------------- ### Use an HTTP Proxy Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/quickstart.md Send a GET request through an HTTP proxy. Requires the `proxy` feature to be enabled. ```rust fn main() -> Result<(), Box> { let proxy = minreq::Proxy::new("proxy.example.com:3128")?; let response = minreq::get("http://example.com") .with_proxy(proxy) .send()?; Ok(()) } ``` -------------------------------- ### Error Handling Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Illustrates how to handle potential errors during request sending and response processing using Rust's `Result` type. ```rust use minreq::get; fn main() { match get("https://httpbin.org/get").send() { Ok(response) => { println!("Success! Status: {}", response.status_code()); } Err(error) => { eprintln!("An error occurred: {}", error); // You can inspect the error type for more details // match error { // minreq::Error::Transport(_) => eprintln!("Network error"), // minreq::Error::Status(_) => eprintln!("Bad status code"), // _ => eprintln!("Other error"), // } } } } ``` -------------------------------- ### Set Query Parameters Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/quickstart.md Send a GET request with multiple query parameters. Requires the `urlencoding` feature for automatic encoding of parameter values. ```rust fn main() -> Result<(), Box> { let response = minreq::get("http://api.example.com/search") .with_param("q", "rust") .with_param("page", "1") .with_param("limit", "20") .send()?; Ok(()) } ``` -------------------------------- ### Handle Different Response Types Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/quickstart.md Process HTTP responses based on their status code and content type. This example demonstrates handling JSON, text, and binary data. ```rust fn main() -> Result<(), Box> { let response = minreq::get("http://api.example.com").send()?; match response.status_code { 200 => { let content_type = response.header("content-type").unwrap_or("text/plain"); if content_type.contains("application/json") { let json: serde_json::Value = response.json()?; println!("JSON: {}", json); } else if content_type.contains("text") { let text = response.as_str()?; println!("Text: {}", text); } else { let bytes = response.as_bytes(); println!("Binary: {} bytes", bytes.len()); } }, 404 => eprintln!("Not found"), _ => eprintln!("Status: {}", response.status_code), } Ok(()) } ``` -------------------------------- ### Handle PunycodeConversionFailed Error in Rust Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/errors.md This example demonstrates how to handle errors when a non-ASCII domain cannot be encoded to punycode, typically due to invalid characters. It advises checking the domain for valid characters. ```rust match minreq::get("http://invalid\x00domain.jp").send() { Err(minreq::Error::PunycodeConversionFailed) => { eprintln!("Domain contains invalid characters for punycode encoding"); }, _ => {} } ``` -------------------------------- ### Connection Reuse for Bulk Operations Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/connection-and-tls.md This example shows a loop that creates a new connection for each POST request. Minreq does not currently pool connections, so for high-throughput scenarios, consider external pooling libraries. ```rust // Creates multiple connections (one per request) for item in items { let response = minreq::post("http://api.example.com") .with_json(&item)? .send()?; } ``` -------------------------------- ### Error Handling Example Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/types.md Demonstrates how to handle different `Error` variants returned by the `request.send()` method, including specific cases like `HttpsFeatureNotEnabled` and `InvalidUtf8InBody`. ```rust match request.send() { Ok(response) => { /* handle response */ }, Err(Error::HttpsFeatureNotEnabled) => { eprintln!("Enable HTTPS feature") }, Err(Error::InvalidUtf8InBody(utf8_err)) => { eprintln!("Binary response: {}", utf8_err) }, Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Access Status Code and Reason Phrase Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/response.md Retrieve the numeric status code and the human-readable reason phrase from the server's response. This example shows a match statement for different status codes. ```rust let response = minreq::get("http://example.com/notfound").send()?; match response.status_code { 200 => println!("Success: {}", response.reason_phrase), 404 => println!("Not found: {}", response.reason_phrase), 500 => println!("Server error: {}", response.reason_phrase), code => println!("Status {}: {}", code, response.reason_phrase), } ``` -------------------------------- ### Full Featured minreq Dependency Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/README.md Configure minreq with multiple features for advanced capabilities including HTTPS, JSON handling, URL encoding, punycode, and proxy support. This setup also includes serde and serde_json for JSON processing. ```toml [dependencies] minreq = { version = "3.0", features = [ "https", "json-using-serde", "urlencoding", "punycode", "proxy" ] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" ``` -------------------------------- ### Downloading Large Files with Chunked Encoding Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/response.md Shows how to download a large file, potentially using chunked transfer encoding, and save it to a local file. This example utilizes std::io::copy for efficient data transfer. Ensure the response is sent using send_lazy(). ```Rust use std::io::Read; // Large file download with chunked encoding let mut response = minreq::get("http://example.com/largefile").send_lazy()?; let mut file = std::fs::File::create("largefile.bin")?; std::io::copy(&mut response, &mut file)?; ``` -------------------------------- ### Build Documentation with All Features Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md Use this command to build documentation that includes all available features, providing a complete API view. ```bash cargo doc --all-features --open ``` -------------------------------- ### Create Proxy Instance Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/configuration.md Illustrates how to create a `Proxy` instance for configuring proxy settings. The URL format supports optional authentication credentials and port. ```rust // Proxy URL format: // [http://][user[:password]@]host[:port] minreq::Proxy::new("proxy.example.com:3128")?; minreq::Proxy::new("user:pass@proxy:1080")?; ``` -------------------------------- ### Build Documentation with Minimal Features Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md Build documentation with only the minimal features enabled. ```bash cargo doc --open ``` -------------------------------- ### Basic Authentication with Proxy URL Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/proxy.md Demonstrates how to create a proxy configuration with basic authentication using a URL. The library automatically handles base64 encoding for the Proxy-Authorization header. ```rust let proxy = minreq::Proxy::new("john:secret@proxy.example.com:3128")?; // Becomes: Proxy-Authorization: Basic am9objpzZWNyZXQ= let proxy = minreq::Proxy::new("john@proxy.example.com:3128")?; // Becomes: Proxy-Authorization: Basic am9obg== ``` -------------------------------- ### Configure and Use HTTP Proxy with Minreq Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md This snippet demonstrates how to create a proxy configuration with authentication and attach it to a request, or rely on environment variables for proxy detection. ```rust // Create proxy let proxy = minreq::Proxy::new("user:password@proxy.example.com:3128")?; // Use with request let response = minreq::get("http://example.com") .with_proxy(proxy) .send()?; // Or use environment variable std::env::set_var("http_proxy", "proxy.example.com:3128"); let response = minreq::get("http://example.com").send()?; ``` -------------------------------- ### Get Response Body as Bytes Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/response.md Returns a slice of the response body bytes. Useful for binary data. ```rust let response = minreq::get("http://example.com/binary").send()?; let bytes = response.as_bytes(); println!("Received {} bytes", bytes.len()); ``` -------------------------------- ### Create Proxy Configuration Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/proxy.md Demonstrates creating a new Proxy configuration from a proxy URL string. Supports various formats including basic, authenticated, and scheme-prefixed URLs. ```rust let proxy = minreq::Proxy::new("proxy.example.com:3128")?; ``` ```rust let proxy = minreq::Proxy::new("localhost:1080")?; ``` ```rust let proxy = minreq::Proxy::new("proxy.example.com")?; ``` ```rust let proxy = minreq::Proxy::new("http://proxy.example.com:3128")?; ``` ```rust let proxy = minreq::Proxy::new("user:password@proxy.example.com:3128")?; ``` ```rust let proxy = minreq::Proxy::new("admin:p@ss:w0rd@proxy.example.com:3128")?; ``` -------------------------------- ### Get Response Body as String Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/response.md Converts the response body to a UTF-8 string. Errors if the body contains invalid UTF-8. ```rust let response = minreq::get("http://example.com").send()?; match response.as_str() { Ok(body) => println!("Body: {}", body), Err(e) => eprintln!("Invalid UTF-8 in response: {}", e), } ``` -------------------------------- ### Minimal Minreq Configuration Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md Use this configuration for the smallest possible dependency size, including only the core functionality. ```toml minreq = "3.0" ``` -------------------------------- ### Set Request Timeout Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/quickstart.md Send a GET request with a specified timeout in seconds. If the request takes longer than the timeout, it will be aborted. ```rust fn main() -> Result<(), Box> { let response = minreq::get("http://example.com") .with_timeout(10) // 10 seconds .send()?; Ok(()) } ``` -------------------------------- ### Make Request Through HTTP Proxy with Basic Auth Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/proxy.md Demonstrates how to create a Proxy instance with username and password, and then use it to make an HTTPS request. Ensure the 'proxy' feature is enabled in Cargo.toml. ```rust use minreq::Proxy; fn main() -> Result<(), Box> { // Create proxy with authentication let proxy = Proxy::new("user:password@proxy.company.com:3128")?; // Make request through proxy let response = minreq::get("https://api.github.com/users/github") .with_timeout(10) .with_proxy(proxy) .send()?; println!("Status: {}", response.status_code); println!("Body: {}", response.as_str()?); Ok(()) } ``` -------------------------------- ### Method Enum Usage Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/types.md Demonstrates how to create requests using standard and custom HTTP methods. ```rust // Standard methods let req1 = minreq::Request::new(minreq::Method::Get, "http://example.com"); // Custom method let req2 = minreq::Request::new( minreq::Method::Custom("CUSTOM".to_string()), "http://example.com" ); ``` -------------------------------- ### Handle Case-Insensitive Headers Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/response.md Header field names are case-insensitive. This example demonstrates equivalent lookups and how to iterate over multiple headers with the same field name. ```rust let response = minreq::get("http://example.com").send()?; // All these lookups are equivalent assert_eq!(response.header("content-type"), response.header("Content-Type")); assert_eq!(response.header("CONTENT-TYPE"), response.header("content-type")); // Iterate multiple headers for value in response.headers("set-cookie") { println!("Cookie: {}", value); } ``` -------------------------------- ### Retry HTTP Request with Backoff Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/quickstart.md Implement a retry mechanism for HTTP requests that fail. This example uses exponential backoff to wait between retries. ```rust use std::time::Duration; use std::thread::sleep; fn main() -> Result<(), Box> { const MAX_RETRIES: u32 = 3; for attempt in 1..=MAX_RETRIES { match minreq::get("http://api.example.com").send() { Ok(response) => { if response.status_code == 200 { println!("{}", response.as_str()?); return Ok(()); } }, Err(e) => { if attempt < MAX_RETRIES { eprintln!("Attempt {} failed: {}", attempt, e); sleep(Duration::from_secs(2_u64.pow(attempt))); } else { return Err(Box::new(e)); } } } } Ok(()) } ``` -------------------------------- ### Get Single Header Value Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/response.md Retrieves the first value of a specified header field, performing a case-insensitive search. Returns `None` if the header is not found. ```rust let response = minreq::get("http://example.com").send()?; if let Some(content_type) = response.header("content-type") { println!("Content-Type: {}", content_type); } // Case-insensitive lookup assert_eq!( response.header("Content-Type"), response.header("content-type") ); ``` -------------------------------- ### Proxy Configuration Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/README.md Details on how to configure and use HTTP proxies with minreq. ```APIDOC ## Proxy Configuration Details for configuring and using HTTP proxies. ### `Proxy` Type Used to configure proxy settings for requests. #### Methods - `Proxy::new(url)`: Creates a new `Proxy` configuration by parsing a proxy URL string. This requires the `proxy` feature to be enabled. ``` -------------------------------- ### Handle Connection Errors Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/connection-and-tls.md Demonstrates how to match and handle different types of connection errors returned by the `minreq::get().send()` method. This is useful for diagnosing and responding to specific network failures. ```rust match minreq::get("http://example.com").send() { Ok(response) => { /* handle 2xx-5xx */ }, Err(minreq::Error::AddressNotFound) => { /* DNS failed */ }, Err(minreq::Error::IoError(e)) => { /* Network I/O */ }, Err(minreq::Error::HttpsFeatureNotEnabled) => { /* Need HTTPS */ }, Err(e) => { /* Other errors */ }, } ``` -------------------------------- ### Disable Redirects Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/quickstart.md Send a GET request and explicitly disable the automatic following of HTTP redirects. The response will contain the redirect status code and location header if applicable. ```rust fn main() -> Result<(), Box> { let response = minreq::get("http://example.com") .with_follow_redirects(false) .send()?; if response.status_code == 301 || response.status_code == 302 { if let Some(location) = response.header("location") { println!("Redirected to: {}", location); } } Ok(()) } ``` -------------------------------- ### Request Constructor Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/request-methods.md Creates a new HTTP Request with the specified method and URL. This is the entry point for building requests. ```APIDOC ## Request Constructor ### Description Creates a new HTTP `Request` with the specified method and URL. ### Method `new` ### Signature ```rust pub fn new>(method: Method, url: T) -> Request ``` ### Parameters #### Path Parameters - **method** (`Method`) - Required - The HTTP method (GET, POST, PUT, DELETE, etc.) - **url** (`T: Into`) - Required - The URL to request. Accepts `String` or `&str` ### Return Type `Request` ### Defaults Applied on Creation - `timeout`: `None` (no timeout) - `max_headers_size`: `Some(8192)` bytes - `max_status_line_len`: `Some(8192)` bytes - `max_redirects`: `100` - `follow_redirects`: `true` ### Example ```rust let request = minreq::Request::new( minreq::Method::Get, "http://example.com" ); ``` ``` -------------------------------- ### Convenience Functions for HTTP Methods Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/request-methods.md These functions simplify the creation of HTTP requests by pre-setting the HTTP method. They accept a URL and return a `Request` object ready to be configured and sent. ```APIDOC ## GET ### Description Creates a `Request` object for a GET request. ### Method GET ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust minreq::get("http://example.com").send()?; ``` ## POST ### Description Creates a `Request` object for a POST request. ### Method POST ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Optional. Can be set using `.with_body()` or `.with_json()`. ### Request Example ```rust minreq::post("http://example.com").with_body("data").send()?; ``` ## PUT ### Description Creates a `Request` object for a PUT request. ### Method PUT ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Optional. Can be set using `.with_body()` or `.with_json()`. ### Request Example ```rust // Assuming `data` is a serializable value // minreq::put("http://example.com/1").with_json(&data)?.send()?; ``` ## DELETE ### Description Creates a `Request` object for a DELETE request. ### Method DELETE ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust minreq::delete("http://example.com/1").send()?; ``` ## HEAD ### Description Creates a `Request` object for a HEAD request. ### Method HEAD ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // minreq::head("http://example.com").send()?; ``` ## CONNECT ### Description Creates a `Request` object for a CONNECT request. ### Method CONNECT ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // minreq::connect("http://example.com").send()?; ``` ## OPTIONS ### Description Creates a `Request` object for an OPTIONS request. ### Method OPTIONS ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // minreq::options("http://example.com").send()?; ``` ## TRACE ### Description Creates a `Request` object for a TRACE request. ### Method TRACE ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // minreq::trace("http://example.com").send()?; ``` ## PATCH ### Description Creates a `Request` object for a PATCH request. ### Method PATCH ### Endpoint [URL] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body Optional. Can be set using `.with_body()` or `.with_json()`. ### Request Example ```rust // Assuming `data` is a serializable value // minreq::patch("http://example.com/1").with_json(&data)?.send()?; ``` ``` -------------------------------- ### Add JSON and Serde Dependencies Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md Include these dependencies in your Cargo.toml to enable JSON serialization and deserialization with minreq. ```toml [dependencies] minreq = { version = "3.0", features = ["json-using-serde"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" ``` -------------------------------- ### Handling InvalidProtocolInRedirect Error Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/errors.md Illustrates catching an `InvalidProtocolInRedirect` error. This error is triggered when a server redirects to a URL that does not start with `http://` or `https://`, such as a malformed `Location` header. ```rust // If server redirects to an invalid protocol match minreq::get("http://example.com").send() { Err(minreq::Error::InvalidProtocolInRedirect) => { eprintln!("Server redirected to unsupported protocol"); }, _ => {} } ``` -------------------------------- ### Full Featured Minreq Configuration Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md Includes HTTPS, JSON, URL encoding, Punycode, and proxy support for comprehensive web functionality. ```toml minreq = { version = "3.0", features = [ "https", "json-using-serde", "urlencoding", "punycode", "proxy" ]} ``` -------------------------------- ### Line-by-Line Streaming Response in Rust Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/quickstart.md Demonstrates how to lazily send a request and stream the response body line by line, useful for processing large text-based responses efficiently. ```rust use std::io::BufRead; fn main() -> Result<(), Box> { let response = minreq::get("http://example.com/lines").send_lazy()?; let reader = std::io::BufReader::new(response); for line in reader.lines() { let line = line?; println!("Line: {}", line); } Ok(()) } ``` -------------------------------- ### Enable HTTPS with Vendored OpenSSL Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md Use this feature for HTTPS requests with a statically vendored OpenSSL library. Manual root certificate configuration via environment variables is required. ```toml [dependencies] minreq = { version = "3.0", features = ["https-openssl"] } ``` -------------------------------- ### Stream Large Response to File Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/quickstart.md Lazily send a GET request and stream the response body directly to a file. This is efficient for large files as it avoids loading the entire response into memory. ```rust use std::io::Read; fn main() -> Result<(), Box> { let mut response = minreq::get("http://example.com/file.bin") .send_lazy()?; let mut file = std::fs::File::create("file.bin")?; std::io::copy(&mut response, &mut file)?; Ok(()) } ``` -------------------------------- ### Handling InvalidProtocol Error Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/errors.md Demonstrates how to catch an `InvalidProtocol` error, which occurs when a URL does not start with `http://` or `https://`. This can happen with missing schemes, malformed URLs, or empty URLs. ```rust // Triggers InvalidProtocol match minreq::get("example.com").send() { Err(minreq::Error::InvalidProtocol) => { eprintln!("URL must start with http:// or https://"); }, _ => {} } ``` -------------------------------- ### Basic Web Features for Minreq Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md Enable basic web capabilities by including HTTPS and JSON support using Serde. ```toml minreq = { version = "3.0", features = ["https", "json-using-serde"] } ``` -------------------------------- ### Handle BadProxy Error in Rust Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/errors.md Catch and handle the `BadProxy` error when a proxy URL is malformed or uses an unsupported scheme. This example shows how to check for this specific error and provide user feedback. ```rust match minreq::Proxy::new("invalid-proxy-format") { Err(minreq::Error::BadProxy) => { eprintln!("Proxy format: [http://][user[:pass]@]host[:port]"); }, Ok(proxy) => { minreq::get("http://example.com").with_proxy(proxy).send()?; } } ``` -------------------------------- ### Enable Proxy Feature in Cargo.toml Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/proxy.md Shows how to enable the 'proxy' feature for the Minreq dependency in your Cargo.toml file to use proxy functionality. ```toml [dependencies] minreq = { version = "3.0", features = ["proxy"] } ``` -------------------------------- ### Proxy Configuration Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md The `Proxy` type provides complete configuration options for setting up and using proxies. ```APIDOC ## Proxy Configuration ### Description Provides comprehensive configuration for proxy settings. ### Type - `Proxy` ``` -------------------------------- ### Proxy::new Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/proxy.md Creates a new Proxy configuration from a proxy URL string. Supports various formats including optional scheme, authentication, and port. ```APIDOC ## Proxy::new ### Description Creates a new Proxy configuration from a proxy URL string. Supports various formats including optional scheme, authentication, and port. ### Method Rust function call ### Signature `pub fn new>(proxy: S) -> Result` ### Parameters #### Path Parameters - **proxy** (S: AsRef) - Required - Proxy URL in one of the supported formats. ### Supported Formats - `[http://][user[:password]@]host[:port]` - `http://` prefix is optional - User and password are optional for authenticated proxies - Default port is 1080 if not specified - Only the `http://` scheme is supported (not `https://` or `socks://`) ### Errors - `Error::BadProxy` if the proxy format is invalid or uses unsupported scheme ### Request Example ```rust // Simple proxy without authentication let proxy = minreq::Proxy::new("proxy.example.com:3128")?; // With port only let proxy = minreq::Proxy::new("localhost:1080")?; // With default port 1080 let proxy = minreq::Proxy::new("proxy.example.com")?; // With HTTP scheme prefix let proxy = minreq::Proxy::new("http://proxy.example.com:3128")?; // With basic authentication let proxy = minreq::Proxy::new("user:password@proxy.example.com:3128")?; // Complex credentials with special characters let proxy = minreq::Proxy::new("admin:p@ss:w0rd@proxy.example.com:3128")?; ``` ### Response #### Success Response - **Proxy** - A new Proxy configuration object. #### Response Example ```rust // Successful creation returns a Proxy object let proxy = minreq::Proxy::new("proxy.example.com:3128")?; ``` ``` -------------------------------- ### Enable or Disable Redirect Following Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/configuration.md Use `with_follow_redirects` to toggle automatic redirect handling. When disabled, the application must manually process redirects. For 303 responses, POST/PUT/DELETE methods are changed to GET. ```rust # Automatically follow redirects (default) let response = minreq::get("http://example.com").send()?; ``` ```rust # Disable redirects and handle manually let response = minreq::get("http://example.com") .with_follow_redirects(false) .send()?; if response.status_code == 301 || response.status_code == 302 { if let Some(location) = response.header("location") { eprintln!("Redirected to: {}", location); // Follow redirect manually minreq::get(location).send()?; } } ``` -------------------------------- ### Using Environment Variables in Rust Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/proxy.md Illustrates how to set environment variables programmatically in Rust before making a request. The minreq library will automatically pick up these variables to route the request through the specified proxy. ```rust std::env::set_var("http_proxy", "proxy.example.com:3128"); let response = minreq::get("http://example.com").send()?; ``` -------------------------------- ### Handle InvalidUtf8InBody Error in Rust Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/errors.md This example demonstrates how to handle responses that are not valid UTF-8 when attempting to convert them to a string using `as_str()`. It shows how to catch the InvalidUtf8InBody error and fall back to using `as_bytes()` for binary data. ```rust let response = minreq::get("http://example.com/binary.jpg").send()?; match response.as_str() { Err(minreq::Error::InvalidUtf8InBody(utf8_err)) => { eprintln!("Response is binary: {}", utf8_err); // Use as_bytes() instead let bytes = response.as_bytes(); }, Ok(text) => println!("Text response: {}", text), } ``` -------------------------------- ### Send Request and Collect Full Response Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/request-methods.md Use `send()` to fetch a response and load its entire body into memory. This is suitable for smaller responses. Be cautious with large downloads as it can consume significant memory. ```rust let response = minreq::get("http://example.com").send()?; println!("Status: {}", response.status_code); println!("Body: {}", response.as_str()?); ``` -------------------------------- ### Enable HTTPS with Native TLS Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md This feature enables HTTPS by utilizing the operating system's native TLS library (SChannel on Windows, Security Framework on macOS, OpenSSL on Linux). It offers the best OS integration and minimal setup. ```toml [dependencies] minreq = { version = "3.0", features = ["https-native-tls"] } ``` -------------------------------- ### Convenience Functions for Request Methods Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/request-methods.md Provides functions to easily create Request instances for common HTTP methods. These functions accept any type convertible to URL. ```rust pub fn get>(url: T) -> Request ``` ```rust pub fn head>(url: T) -> Request ``` ```rust pub fn post>(url: T) -> Request ``` ```rust pub fn put>(url: T) -> Request ``` ```rust pub fn delete>(url: T) -> Request ``` ```rust pub fn connect>(url: T) -> Request ``` ```rust pub fn options>(url: T) -> Request ``` ```rust pub fn trace>(url: T) -> Request ``` ```rust pub fn patch>(url: T) -> Request ``` -------------------------------- ### Handle Proxy Creation and Usage Errors in Rust Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/proxy.md Demonstrates how to handle potential errors when creating a proxy object and when using a proxy to send an HTTP request. Catches specific proxy errors like BadProxy, InvalidProxyCreds, and ProxyConnect. ```rust match minreq::Proxy::new("invalid-proxy") { Ok(proxy) => { /* use proxy */ }, Err(minreq::Error::BadProxy) => eprintln!("Invalid proxy format"), Err(e) => eprintln!("Proxy error: {}", e), } match minreq::get("http://example.com") .with_proxy(proxy) .send() { Ok(response) => { /* success */ }, Err(minreq::Error::InvalidProxyCreds) => eprintln!("Proxy auth failed"), Err(minreq::Error::ProxyConnect) => eprintln!("Could not reach proxy"), Err(e) => eprintln!("Other error: {}", e), } ``` -------------------------------- ### Configuration Methods Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/DOCUMENTATION_INDEX.md Methods available for configuring requests, including headers, bodies, timeouts, and more. ```APIDOC ## Configuration Methods ### Description Methods to customize request configurations. ### Methods - `with_header(header)` - `with_headers(headers)` - `with_body(body)` - `with_json(json)` (feature: json-using-serde) - `with_param(param)` - `with_timeout(timeout)` - `with_max_redirects(max_redirects)` - `with_follow_redirects(follow)` - `with_max_headers_size(size)` - `with_max_status_line_length(length)` - `with_proxy(proxy)` (feature: proxy) ``` -------------------------------- ### Full Featured Compilation with Multiple HTTPS Options Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/api-reference/connection-and-tls.md Illustrates enabling a comprehensive set of features for minreq, including multiple HTTPS backends (rustls, native-tls, openssl), JSON support, punycode, proxy, and URL encoding. Note that typically only one HTTPS feature is used per deployment. ```toml [dependencies] minreq = { version = "3.0", features = [ "https-rustls", "https-native-tls", "https-openssl", "json-using-serde", "punycode", "proxy", "urlencoding" ] } ``` -------------------------------- ### Enable HTTPS with Vendored OpenSSL and Auto-Detection Source: https://github.com/neonmoe/minreq/blob/master/_autodocs/features.md This feature combines vendored OpenSSL with automatic system certificate detection. It finds system certs automatically but falls back to environment variables, resulting in a larger binary size and slower startup. ```toml [dependencies] minreq = { version = "3.0", features = ["https-openssl-probe"] } ```