如何使用 reqwest 包

GET 请求

向连接发起一个 GET 请求:https://hacker-news.firebaseio.com/v0/topstories.json,并解析返回的内容。

尝试发起请求

因为是 GET 请求,可以先在浏览器中进行查看,浏览器可以正常显示一个 id 列表,如下所示。我们开始 coding

[
    37020001,
    37020421,
    36992775
]

首先,编辑 Cargo.toml 中 dependencies,指定项目需要的依赖:

[dependencies]
reqwest = "0.11.18"
serde_json = "1.0.33"
futures = "0.3"

我拼凑了下面代码,虽然耗费了很大的气力,但运行不起来,仔细观察运行提示,过程中发生 panic。加上不怎么熟悉 VSC 这个编译器,也不能完全发挥 VSC 的排查能力。

use reqwest::Client;
use serde_json::Value;
use std::sync::Arc;
use futures::executor::block_on;

fn main() {
    let client = Arc::new(reqwest::Client::new());
    let control = get_story_ids(client.clone());
    block_on(control); 
}

async fn get_story_ids(client: Arc<Client>) {
    let stories_url = format!(
        "{}",
        "https://hacker-news.firebaseio.com/v0/topstories.json"
    );
    
    let body = client
        .get(&stories_url)
        .send()
        .await
        .unwrap()
        .text()
        .await.unwrap();

    let story_ids: Value = serde_json::from_str(&body).unwrap();
    println!("{:#?}", story_ids);
}

这段代码使用到了 reqwest、Arc、futures、serde_json,暂时不考虑代码使用的合理性。现在首要的工作是:要这段代码正常执行。

在这里插入图片描述

panic 问题处理

设置 RUST_BACKTRACE 环境变量,控制台输出 trace 调用栈信息。虽然调用栈显示出来了,但看不懂也没有用。

RUST_BACKTRACE=1 cargo run 

tokio 1.x 是干什么用的,there is no reactor running 这又是指代什么?

你可能感兴趣的:(rust,编程开发,rust)