I would like to be able to keep the cookie of a previous request for the next one :
let hyper_client = Client::new();
server_response = hyper_client.request(Method::Get, url).headers(Headers::new()).send();
Assuming the code above compile, how could I retrieve the cookie of this session ?
Something like this should work:
match server_response.headers.get() {
Some(&SetCookie(ref content)) => println!("Cookie: {:?}", content),
_ => println!("No cookie found"),
}
Use the Cookie
header for cookies sent to the server, and SetCookie
for cookies sent from the server. I'm emphasising that because I only saw Cookie
at first and it caught me out.
Also, notice that I am requesting the SetCookie
header just by type inference from the pattern match. I could also have used the turbo-fish: headers.get::<SetCookie>()
.
If you need to send the same cookie back the server, you can just clone the SetCookie
values from the response back into a new Cookie
header for the request:
let mut headers = Headers::new();
// if you received cookies in the server response then send the same ones back
if let Some(&SetCookie(ref content)) = server_response.headers.get() {
headers.set(Cookie(content.clone()));
}
hyper_client.request(Method::Get, url)
.headers(headers)
.send();