MST
星途 面试题库

面试题:Rust使用hyper进行HTTP客户端开发之基础请求

在Rust中,使用hyper库发起一个简单的GET请求到指定URL,并打印响应状态码和响应体内容,简要描述代码实现步骤并给出关键代码片段。
19.5万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
  1. 添加依赖: 在Cargo.toml文件中添加hyper库依赖:
    [dependencies]
    hyper = "0.14"
    
  2. 编写请求代码
    • 引入必要的模块。
    • 创建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。