2

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 ?

Le Duc Banal
  • 53
  • 11

1 Answers1

0

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();
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • Great I can retrieve it now ! But I can't reuse it... I tried to do `headers.set(content)` and... it doesn't work... I think that I confuse `SetCookie` and `Cookie`, some help ? – Le Duc Banal Feb 26 '17 at 15:19
  • I've added an example of sending the same cookie values back to the server – Peter Hall Feb 26 '17 at 18:52
  • 1
    This answer seems to be outdated, since ``hyper::client::Client`` doesn't implemented a method which takes two parameters. – Philipp Ludwig Mar 19 '18 at 15:26
  • @PeterHall cookie functionality [was removed](https://github.com/hyperium/hyper/issues/1536) from hyper, isn't it? – diralik Mar 22 '19 at 21:50