面试题答案
一键面试- 添加依赖:
在
Cargo.toml
文件中添加hyper
库依赖:[dependencies] hyper = "0.14"
- 编写请求代码:
- 引入必要的模块。
- 创建
Client
实例。 - 发起GET请求并处理响应。
关键代码片段如下:
use hyper::{Client, Uri};
use hyper::body::to_bytes;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = Client::new();
let uri = Uri::try_from("https://example.com")?;
let response = client.get(uri).await?;
let status = response.status();
let body = to_bytes(response.into_body()).await?;
println!("Status: {}", status);
println!("Body: {}", std::str::from_utf8(&body)?);
Ok(())
}
上述代码中,使用hyper
库的Client
发送GET请求到https://example.com
,获取并打印响应状态码和响应体内容。实际使用时将https://example.com
替换为目标URL。