一个 Rust HttpClient 例子

在 cargo.toml 文件中添加

1
2
[dependencies]
hyper = "0.7.2"

src 中创建 main.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
extern crate hyper;

use std::io::Read;
use hyper::Client;

fn main() {println!("welcome to rust http");
let client = Client::new();
let mut res = client.get("https://httpbin.org/get").send().unwrap();
assert_eq!(res.status, hyper::Ok);
println!("headers:\n {}", res.headers);
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
println!("body:\n {}", body);
res = client.post("https://httpbin.org/post").body("{\"a\":1}").send().unwrap();
assert_eq!(res.status, hyper::Ok);
println!("headers:\n {}", res.headers);
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
println!("body:\n {}", body);
}

执行 cargo build 后执行 ./target/debug / 项目名 即可看到效果。