Accept cookise in an HTTP request sent by the server

Rust
curl -i "http://httpbin.org/cookies/set?name=Foo+Bar"

In this request we asked the httpbin server to send us a cookie (normally this is the decision of the server, but the httpbin server is here to help us).

Output (showing only the header part) where we can see the row Set-Cookie, that is setting a cookie in our "broswer".

HTTP/1.1 302 FOUND
Date: Thu, 25 Jan 2024 13:22:52 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 223
Connection: keep-alive
Server: gunicorn/19.9.0
Location: /cookies
Set-Cookie: name="Foo Bar"; Path=/
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

Dependencies

examples/reqwest-accept-cookies/Cargo.toml

[package]
name = "reqwest-accept-cookies"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
reqwest = { version = "0.11", features = ["blocking"] }

The code

examples/reqwest-accept-cookies/src/main.rs

use reqwest::header::USER_AGENT;

fn main() {
    let custom = reqwest::redirect::Policy::custom(|attempt| { attempt.stop() });

    //let client = reqwest::blocking::Client::new();
    let client = reqwest::blocking::Client::builder()
    .redirect(custom)
    .build().unwrap();

    let res = client
    .get("http://httpbin.org/cookies/set?name=Foo")
    .header(USER_AGENT, "Rust Maven 1.42")
    .send().unwrap();
    //println!("{}", res.text().unwrap());
    //let c = res.headers().get("Date").unwrap();
    println!("{}", res.headers().get("Date").unwrap().to_str().unwrap());
    println!("{}", res.headers().get("set-cookie").unwrap().to_str().unwrap());
    for (name, value) in res.headers() {
        println!("{}", name.as_str());
    }
}

The output

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo