你如何在Rust中提出GET请求?

Jos*_*ein 15 get http rust

我注意到Rust没有内置库来处理HTTP,它只有一个net处理原始IP和TCP协议的模块.

我需要获取一个&strURL,发出一个HTTP GET请求,如果成功返回一个String&str那个对应于HTML或JSON或其他字符串形式的响应.

它看起来像:

use somelib::http;

let response = http::get(&"http://stackoverflow.com");
match response {
    Some(suc) => suc,
    None => panic!
}
Run Code Online (Sandbox Code Playgroud)

Jan*_*son 10

看看Hyper.

发送GET请求就像这样简单.

let client = Client::new();

let res = client.get("http://example.domain").send().unwrap();
assert_eq!(res.status, hyper::Ok);
Run Code Online (Sandbox Code Playgroud)

您可以在文档中找到更多示例.

编辑:由于他们开始使用Tokio,似乎Hyper变得有点复杂.这是更新版本.

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

use std::io::{self, Write};
use futures::{Future, Stream};
use hyper::Client;
use tokio_core::reactor::Core;


fn main() {
    let mut core = Core::new().unwrap();
    let client = Client::new(&core.handle());

    let uri = "http://httpbin.org/ip".parse().unwrap();
    let work =
        client.get(uri).and_then(|res| {
            println!("Response: {}", res.status());

            res.body().for_each(|chunk| {
                io::stdout()
                    .write_all(&chunk)
                    .map_err(From::from)
            })
        });
    core.run(work).unwrap();
}
Run Code Online (Sandbox Code Playgroud)

这是必需的依赖项.

[dependencies]
futures = "0.1"
hyper = "0.11"
tokio-core = "0.1"
Run Code Online (Sandbox Code Playgroud)

  • 这不再有效,因为`hyper :: Client :: new`需要一些句柄参数. (8认同)

nin*_*alf 7

针对此特定问题的当前最佳实践是使用reqwestRust Cookbook中指定的板条箱。该代码略有修改,可独立运行:

extern crate reqwest; // 0.9.18

use std::io::Read;

fn run() -> Result<(), Box<dyn std::error::Error>> {
    let mut res = reqwest::get("http://httpbin.org/get")?;
    let mut body = String::new();
    res.read_to_string(&mut body)?;

    println!("Status: {}", res.status());
    println!("Headers:\n{:#?}", res.headers());
    println!("Body:\n{}", body);

    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

如本食谱所述,此代码将同步执行。

也可以看看:


Lui*_*tin 6

尝试去 reqwest:

extern crate reqwest;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut res = reqwest::get("https://httpbin.org/headers")?;

    // copy the response body directly to stdout
    std::io::copy(&mut res, &mut std::io::stdout())?;

    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

  • 以前的答案不能编译这个,但现在可以:) (10认同)
  • 伟大的!但由于我是新用户,我无法评论之前的答案,也无法编辑它。 (4认同)