Last active
October 6, 2017 07:38
-
-
Save jbolila/d74e50671e2ac7eb82e4ffa3d889995d to your computer and use it in GitHub Desktop.
SetCookie for the next HTTP request using reqwest 0.8.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate reqwest; | |
extern crate cookie; | |
use std::time::Duration; | |
use cookie::{Cookie, CookieJar}; | |
use reqwest::header::{Headers, SetCookie, UserAgent}; | |
fn construct_headers(cookies: &SetCookie) -> Headers { | |
let mut headers = Headers::new(); | |
headers.set(UserAgent::new("autotool")); | |
let mut jar = CookieJar::new(); | |
for cookie in cookies.iter() { | |
jar.add_original(Cookie::parse(cookie.to_owned()).unwrap()); | |
} | |
let mut cookie = reqwest::header::Cookie::new(); | |
for cc in jar.iter() { | |
if cc.name().starts_with("::SID:") { | |
cookie.append(cc.name().to_string(), cc.value().to_string()); | |
} | |
} | |
if cookie.iter().count() > 0 { | |
headers.set(cookie); | |
} | |
headers | |
} | |
fn try_main() -> Result<(), Box<::std::error::Error>> { | |
let client = reqwest::Client::builder() | |
.gzip(true) | |
.redirect(reqwest::RedirectPolicy::none()) | |
.timeout(Duration::from_secs(10)) | |
.build()?; | |
let url = "https://httpbin.org/cookies/set?k1=v1&::SID:REREWEW@#@#@$#&k2=v2"; | |
let response = client.head(url).send()?; | |
println!( | |
"Status-Code: {}\n{:#?}", | |
response.status(), | |
response.headers() | |
); | |
let cookies = response.headers().get::<SetCookie>().ok_or( | |
"cookie not set by the server", | |
)?; | |
println!("{:?} H", construct_headers(cookies)); | |
Ok(()) | |
} | |
fn main() { | |
try_main().unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment