Rust 使用 reqwest 发送 POST 请求并提取 JSON 响应中的多个 completion 值
Rust 发送 POST 请求并提取多个 JSON 响应中的 completion 值
本示例演示了如何使用 Rust 的 reqwest 库发送 POST 请求,并将响应中的多个 JSON 对象中的 'completion' 值提取并合并为单个字符串。
use reqwest::{Client, HeaderMap, Method};
use serde_json::json;
use regex::Regex;
async fn send_post() -> Result<String, reqwest::Error> {
let client = reqwest::Client::new();
// POST 请求头
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"));
// POST 请求体
let data = json!({"prompt": "hello"});
Ok(client.post("https://free-api.cveoy.com/v3/completions")
.headers(header)
.json(&data)
.send()
.await?
.text()
.await?
)
}
async fn get_completion() -> Result<String, reqwest::Error> {
let response = send_post().await?; let re = Regex::new(r#"\{"completion":"(.*?)"\}"#).unwrap();
let mut completions = Vec::new();
for capture in re.captures_iter(&response) {
completions.push(capture[1].to_string());
}
Ok(completions.join(""))
}
代码中使用了 reqwest 库发送 POST 请求,并通过 regex 库匹配响应中的所有 'completion' 值。
关键步骤:
- 发送 POST 请求: 使用
reqwest::Client::new()创建一个客户端,并使用client.post()发送 POST 请求。 - 构建请求头: 使用
HeaderMap添加请求头,例如 User-Agent 和 referer。 - 构建请求体: 使用
serde_json::json!()将请求体构建为 JSON 格式。 - 解析响应: 使用
response.text().await?将响应解析为字符串。 - 匹配 completion 值: 使用
regex::Regex::new()创建一个正则表达式,用于匹配响应中的 'completion' 值。 - 提取 completion 值: 使用
re.captures_iter()迭代匹配到的结果,并将 'completion' 值添加到一个字符串数组中。 - 合并 completion 值: 使用
completions.join("")将所有 'completion' 值合并成一个字符串。
注意:
- 此代码示例仅演示了如何提取 'completion' 值,具体的逻辑需要根据实际需求进行调整。
- 为了保证代码的安全性,请使用官方库,并确保代码的可靠性。
- 正则表达式
r#"\{"completion":"(.*?)"\}"#用于匹配包含 'completion' 的 JSON 对象,其中(.*?)用于捕获 'completion' 的值。
总结:
本示例展示了如何使用 Rust 的 reqwest 和 regex 库来发送 POST 请求并提取响应中的多个 JSON 对象的 'completion' 值。通过使用正则表达式,我们可以轻松地从响应字符串中提取出所需的信息。
希望本示例能够帮助您理解如何使用 Rust 处理网络请求和解析 JSON 数据。
原文地址: https://www.cveoy.top/t/topic/lBP3 著作权归作者所有。请勿转载和采集!