请求处理
发出 HTTP GET 请求
解析提供的 URL,并使用 reqwest::blocking::get
发起同步 HTTP GET 请求。打印获取的响应消息状态和标头 reqwest::blocking::Response
。使用 read_to_string
将 HTTP 响应消息主体正文读入到指派的字符串 String
。
use error_chain::error_chain;
use std::io::Read;
error_chain! {
foreign_links {
Io(std::io::Error);
HttpRequest(reqwest::Error);
}
}
fn main() -> Result<()> {
let mut res = reqwest::blocking::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(())
}
异步
常见的方法是通过包含 tokio
在内的类似异步执行器,使主函数执行异步,但检索处理相同的信息。
本实例中,tokio::main
处理所有繁重的执行器设置,并允许在 .await
之前不阻塞的按顺序执行代码。
也可以使用 reqwest 的异步版本,其请求函数 reqwest::get
和响应结构体 reqwest::Response
都是异步的。
use error_chain::error_chain;
error_chain! {
foreign_links {
Io(std::io::Error);
HttpRequest(reqwest::Error);
}
}
#[tokio::main]
async fn main() -> Result<()> {
let res = reqwest::get("http://httpbin.org/get").await?;
println!("Status: {}", res.status());
println!("Headers:\n{:#?}", res.headers());
let body = res.text().await?;
println!("Body:\n{}", body);
Ok(())
}
为 REST 请求设置自定义消息标头和 URL 参数
本实例中为 HTTP GET 请求设置标准的和自定义的 HTTP 消息标头以及 URL 参数。使用 hyper::header!
宏创建 XPoweredBy
类型的自定义消息标头。
使用 Url::parse_with_params
构建复杂的 URL。使用 RequestBuilder::header
方法设置标准消息标头 header::UserAgent
、header::Authorization
,以及自定义类型 XPoweredBy
,然后使用 RequestBuilder::send
发起请求。
请求的服务目标为 http://httpbin.org/headers,其响应结果是包含所有请求的消息标头的 JSON 字典,易于验证。