2

我正在尝试使用 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);
}
4

2 回答 2

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

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

于 2016-01-03T13:52:38.293 回答
1

使用最新的 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();
}
于 2017-10-16T23:13:25.770 回答