使用 Hyper 发出请求时如何设置 User-Agent header?

How do I set the User-Agent header when making a request with Hyper?

我正在尝试使用 Hyper 库向 Github 的 API 发出 GET 请求,并在 header 中使用 user-agent 字符串.我没有用 .header(UserAgent("string")) 编译。有人愿意提出一种惯用的方法来完成我想要的吗?

extern crate hyper;

use std::io::Read;

use hyper::Client;
use hyper::header::{Connection, Headers};

struct Subtasks {
    github: &'static str,
}

struct Tasks {
    rust: Subtasks,
    go:   Subtasks,
}

fn main() {
    // initialize struct and populate
    let tasks = Tasks {
        rust: Subtasks {
            github: "https://api.github.com/rust-lang/rust",
        },
        go: Subtasks {
            github: "https://api.github.com/golang/go",
        },
    };

    let client = Client::new();
    let mut result = client.get(tasks.rust.github)
        .header(Connection::close())
        .send()
        .unwrap();

    let mut body = String::new();
    result.read_to_string(&mut body).unwrap();

    println!("Response: {}", body);
}

也许您遇到了此类错误?

src/main.rs:31:20: 31:28 error: mismatched types:
 expected `collections::string::String`,
    found `&'static str`
(expected struct `collections::string::String`,
    found &-ptr) [E0308]
src/main.rs:31  .header(UserAgent("string"))

如果是这样,您可以使用

让它工作
.header(UserAgent("string".to_string()))

并将UserAgent纳入范围

use hyper::header::{Connection, Headers, UserAgent};

问题出在构造 header 时使用字符串文字而不是 String,这通过调用字符串文字上的 to_string() 方法解决.

使用较新的 hyper 0.11,您可以像这样设置用户代理:

let mut req = hyper::Request::new(hyper::Method::Get, url);
req.headers_mut().set(UserAgent::new("my agent"));

转换为以下依赖项:

hyper = "0.11"
hyper-tls = "0.1"
tokio-core = "0.1"
futures = "0.1"

整个例子将是:

extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
extern crate futures;

use std::io::{self, Write};

use futures::Future;
use futures::stream::Stream;

use hyper::Client;
use hyper::header::UserAgent;

struct Subtasks {
    github: &'static str,
}

struct Tasks {
    rust: Subtasks,
    go:   Subtasks,
}

fn main() {
    // initialize struct and populate
    let tasks = Tasks {
        rust: Subtasks {
            github: "https://api.github.com/rust-lang/rust",
        },
        go: Subtasks {
            github: "https://api.github.com/golang/go",
        },
    };

    let mut core = tokio_core::reactor::Core::new().unwrap();
    let handle = core.handle();
    let client = Client::configure()
        .connector(hyper_tls::HttpsConnector::new(4, &handle).unwrap())
        .build(&handle);

    let url = tasks.rust.github.parse::<hyper::Uri>().unwrap();
    let mut req = hyper::Request::new(hyper::Method::Get, url);
    req.headers_mut().set(UserAgent::new("my agent"));

    let work = client.request(req).and_then(|res| {
        print!("Response: ");
        res.body().for_each(|chunk| {
            io::stdout().write_all(&chunk).map_err(From::from)
        })
    });

    core.run(work).unwrap();
}