如何从GET响应中获取cookie? [英] How to get the cookie from a GET response?
问题描述
我正在编写一个向网站发出GET请求并返回响应cookie的函数:
I am writing a function that makes a GET request to a website and returns the response cookie:
extern crate futures;
extern crate hyper;
extern crate tokio_core;
use tokio_core::reactor::Core;
use hyper::Client;
use std::error::Error;
use hyper::header::Cookie;
use futures::future::Future;
fn get_new_cookie() -> Result<String, Box<Error>> {
println!("Getting cookie...");
let core = Core::new()?;
let client = Client::new(&core.handle());
println!("Created client");
let uri = "http://www.cnn.com".parse().expect("Cannot parse url");
println!("Parsed url");
let response = client.get(uri).wait().expect("Cannot get url.");
println!("Got response");
let cookie = response
.headers()
.get::<Cookie>()
.expect("Cannot get cookie");
println!("Cookie: {}", cookie);
Ok(cookie)
}
fn main() {
println!("{:?}", get_new_cookie());
}
这不起作用;它停留在 client.get(...)
字符串上。我得到的输出是:
This doesn't work; it is stuck on the client.get(...)
string. The output I'm getting is:
Getting cookie...
Created client
Parsed url
之后没有任何反应。
我做错了什么以及如何更改它以使其有效?
What am I doing wrong and how I can change it so it'd work?
推荐答案
作为< a href =https://stackoverflow.com/a/47854518/155423> Stefan指出,通过调用 wait
,你将线程放到睡到未来完成。但是,该线程需要运行事件循环,因此您只是导致死锁。使用 Core ::运行
更正确。
As Stefan points out, by calling wait
, you are putting the thread to sleep until the future has completed. However, that thread needs to run the event loop, so you've just caused a deadlock. Using Core::run
is more correct.
作为FrancisGagné指出,Cookie标题用于将cookie 发送到服务器。 SetCookie
用于将Cookie 发送到客户端。它还会将所有Cookie的向量一起返回:
As Francis Gagné points out, the "Cookie" header is used to send a cookie to the server. SetCookie
is used to send a cookie to the client. It also returns a vector of all the cookies together:
fn get_new_cookie() -> Result<String, Box<Error>> {
println!("Getting cookie...");
let mut core = Core::new()?;
let client = Client::new(&core.handle());
println!("Created client");
let uri = "http://www.cnn.com".parse().expect("Cannot parse url");
println!("Parsed url");
let response = core.run(client.get(uri)).expect("Cannot get url.");
println!("Got response");
let cookie = response
.headers()
.get::<SetCookie>()
.expect("Cannot get cookie");
println!("Cookie: {:?}", cookie);
Ok(cookie.join(","))
}
但是,如果您只想要同步API,请使用 Reqwest 而不是。它建立在Hyper之上:
However, if you only want a synchronous API, use Reqwest instead. It is built on top of Hyper:
extern crate reqwest;
use std::error::Error;
use reqwest::header::SetCookie;
fn get_new_cookie() -> Result<String, Box<Error>> {
let response = reqwest::get("http://www.cnn.com")?;
let cookies = match response.headers().get::<SetCookie>() {
Some(cookies) => cookies.join(","),
None => String::new(),
};
Ok(cookies)
}
fn main() {
println!("{:?}", get_new_cookie());
}
这篇关于如何从GET响应中获取cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!