在 Rust 中发出 HTTP 请求的最简单方法是使用 reqwest crate:
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let resp = reqwest::blocking::get("https://httpbin.org/ip")?.text()?;
println!("{:#?}", resp);
Ok(())
}
在Cargo.toml:
[dependencies]
reqwest = { version = "0.11", features = ["blocking"] }
异步
Reqwest 还支持使用Tokio 发出异步 HTTP 请求:
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let resp = reqwest::get("https://httpbin.org/ip")
.await?
.text()
.await?;
println!("{:#?}", resp);
Ok(())
}
在Cargo.toml:
[dependencies]
reqwest = "0.11"
tokio = { version = "1", features = ["full"] }
超级
Reqwest 是一个易于使用的 Hyper 包装器,它是 Rust 的流行 HTTP 库。如果您需要对管理连接进行更多控制,您可以直接使用它。下面是一个基于Hyper 的示例,其灵感主要来自an example in its documentation:
use hyper::{body::HttpBody as _, Client, Uri};
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let client = Client::new();
let res = client
.get(Uri::from_static("http://httpbin.org/ip"))
.await?;
println!("status: {}", res.status());
let buf = hyper::body::to_bytes(res).await?;
println!("body: {:?}", buf);
}
在Cargo.toml:
[dependencies]
hyper = { version = "0.14", features = ["full"] }
tokio = { version = "1", features = ["full"] }
原始答案(Rust 0.6)
我相信您正在寻找的是standard library。现在在 rust-http 和 Chris Morgan 的回答是在可预见的未来当前 Rust 的标准方式。我不确定我能带你走多远(希望我没有带你走错方向!),但你会想要这样的东西:
// Rust 0.6 -- old code
extern mod std;
use std::net_ip;
use std::uv;
fn main() {
let iotask = uv::global_loop::get();
let result = net_ip::get_addr("www.duckduckgo.com", &iotask);
io::println(fmt!("%?", result));
}
关于编码,在src/libstd/net_url.rs的单元测试中有一些例子。