Rust 使用 reqwest 发送 POST 请求并解析多个 JSON 响应
use serde_json::{Result, Value};
use std::collections::HashMap;
async fn send_post() -> Result<String, reqwest::Error> {
// 发送POST请求并获取响应
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();
// 添加POST请求体
data.insert('prompt', 'hello');
let response = client.post('https://free-api.cveoy.com/v3/completions')
.headers(header)
.json(&data)
.send()
.await?
.text()
.await?;
// 解析响应中的json数据
let mut completions: Vec<HashMap<String, String>> = Vec::new();
for line in response.lines() {
match serde_json::from_str(line) {
Ok(value) => {
if let Value::Object(hm) = value {
completions.push(hm);
}
},
Err(e) => {
eprintln!('failed to parse json: {}', e);
},
}
}
// 提取completion的值并返回合并后的字符串
let mut result = String::new();
for hm in completions {
if let Some(completion) = hm.get('completion') {
result.push_str(completion);
}
}
Ok(result)
}
该代码使用了 reqwest 库发送 POST 请求,并使用 serde_json 库解析响应中的 JSON 数据。
步骤:
- 使用
reqwest发送 POST 请求并获取响应。 - 使用
serde_json::from_str函数解析响应数据,并将解析后的 JSON 对象存储在一个Vec<HashMap<String, String>>向量中。 - 遍历向量,并提取每个 JSON 对象中的
completion字段的值。 - 将所有
completion值合并成一个字符串。
注意:
- 响应数据是多个独立的 JSON 对象,因此需要将它们逐行解析。
- 为了确保正确解析,请确保每个 JSON 对象都是一个有效的 JSON 格式。
- 该代码假设
completion字段是字符串类型。 - 您可以根据需要修改代码以适应不同的 JSON 结构。
原文地址: https://www.cveoy.top/t/topic/lBPS 著作权归作者所有。请勿转载和采集!