Rust 使用 reqwest 和 serde 获取 API 返回的 JSON 数据
use std::{io, collections::HashMap};
use reqwest::header::HeaderMap;
use serde::{Deserialize, Deserializer};
#[tokio::main]
async fn main() {
match send_post().await {
Ok(res) => {
// 解析返回的 JSON 数据
let data: Vec<Completion> = serde_json::Deserializer::from_str(&res)
.into_iter()
.map(|v| Completion::deserialize(v).unwrap())
.collect();
// 获取 completion 字段的值
let completions: Vec<String> = data.iter().map(|c| c.completion.clone()).collect();
println!('{:#?}', completions);
}
Err(e) => {
eprintln!('{:?}', e)
}
}
}
// 表示一个 completion 对象
#[derive(Debug, Deserialize)]
struct Completion {
#[serde(rename = 'completion')]
completion: String,
}
async fn send_post() -> Result<String, reqwest::Error> {
let client = reqwest::Client::new();
let mut header = HeaderMap::new();
header.insert('User-Agent',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) \
Chrome/110.0.0.0 Safari/537.36'.parse().expect('unsolve the userAgent header value.'),
);
header.insert('referer', 'https//www.covery.com'.parse().expect('unsolve the referer value.'));
header.insert('sec-ch-ua', 'sec-ch-ua'.parse().expect('ms'));
let mut data = HashMap::new();
data.insert('prompt', 'hello');
Ok(client.post('https://free-api.cveoy.com/v3/completions')
.headers(header)
.json(&data)
.send()
.await?
.text()
.await?)
}
为了使用 serde 库,需要在 Cargo.toml 文件中添加以下依赖:
[dependencies]
serde = { version = '1.0', features = ['derive'] }
serde_json = '1.0'
这段代码展示了如何使用 reqwest 发送 HTTP POST 请求,并使用 serde 库解析 API 返回的 JSON 数据。首先,代码定义了一个 Completion 结构体,用于表示一个 JSON 对象。然后,使用 serde_json::Deserializer::from_str 将 JSON 数据解析成 Completion 对象的 Vec。最后,通过遍历 Vec 获取每个 Completion 对象的 completion 字段的值。
需要注意的是,API 的返回数据可能存在多种格式,需要根据具体的 API 文档进行调整代码。
希望这篇文章对您有所帮助。
原文地址: https://www.cveoy.top/t/topic/lBNO 著作权归作者所有。请勿转载和采集!