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

时间:2016-01-03 13:16:58

标签: rust hyper

我尝试使用Hyper库对Rust中的Github API执行GET请求,并在标头中使用用户代理字符串。我没有用.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);
}

2 个答案:

答案 0 :(得分:4)

也许你遇到了这种错误?

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};

问题在于在构造标头时使用字符串文字而不是String,这可以通过调用字符串文字上的to_string()方法来解决。

答案 1 :(得分:1)

使用更新的超级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();
}