Rust 使用 reqwest 发送 POST 请求并解析 JSON 响应
use std::{io, collections::HashMap};
use std::fmt::format;
use std::io::BufRead;
use reqwest::header::HeaderMap;
use serde::{Deserialize};
use serde_derive::Deserialize;
#[tokio::main]
async fn main() {
// let input_buf=get_user_input();
// println!('{}',input_buf);
match send_post().await {
Ok(res)=>{
println!('{:#?}',res);
let data:Vec<Completion>=serde_json::from_str(&res).map_err(|e| format!('Deserialization error: {e}'))?; // 修改此处
let completions:Vec<String>=data.iter().map(|c| c.completion.clone()).collect();
println!('{:#?}',completions);
}
Err(e)=>{eprintln!('{:?}',e)}
}
}
#[derive(Debug, Deserialize)]
struct Completion{
#[serde(rename='completion')]
completion:String,
}
//获取用户键盘输入
fn _get_user_input() -> String {
let mut input_buf = String::new();
let _input = io::stdin().read_line(&mut input_buf).expect('fail to get user input.');
input_buf
}
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 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?
)
}
代码解释:
-
引入必要的库:
std::io:用于获取用户输入std::collections::HashMap:用于构建请求体std::fmt::format:用于格式化错误信息reqwest:用于发送 HTTP 请求serde:用于序列化和反序列化 JSON 数据serde_derive:用于生成Deserializetrait 的宏
-
定义
Completion结构体:- 该结构体用于解析 JSON 响应数据,包含
completion字段
- 该结构体用于解析 JSON 响应数据,包含
-
定义
_get_user_input函数:- 该函数用于获取用户从键盘输入的信息,但本例中没有使用
-
定义
send_post函数:- 该函数用于发送 POST 请求,并返回响应的字符串
- 构建请求头: 使用
HeaderMap构建请求头,设置User-Agent、referer和sec-ch-ua - 构建请求体: 使用
HashMap构建请求体,设置prompt字段为hello - 发送请求: 使用
reqwest::Client发送 POST 请求,设置请求头和请求体 - 获取响应: 使用
await?获取响应,并使用text()方法将响应内容转换为字符串
-
主函数
main:- 使用
tokio::main宏标记该函数为异步函数 - 调用
send_post函数发送请求 - 解析响应: 使用
serde_json::from_str将响应字符串解析为Completion结构体,并处理解析错误 - 打印解析结果: 将
Completion结构体的completion字段打印出来
- 使用
注意:
-
本示例中使用了
await?运算符来处理异步操作,需要在main函数上使用#[tokio::main]宏标记为异步函数。 -
本示例中使用了
serde_derive宏,需要在项目中添加serde和serde_derive的依赖。 -
本示例使用了
reqwest库,需要在项目中添加reqwest的依赖。 -
示例中使用到的 API 接口
https://free-api.cveoy.com/v3/completions是一个免费的 AI 代码补全 API 接口,可以根据请求的prompt字段生成代码建议。', 'content_zh': '```rust use std::{io, collections::HashMap}; use std::fmt::format; use std::io::BufRead; use reqwest::header::HeaderMap; use serde::{Deserialize}; use serde_derive::Deserialize; #[tokio::main] async fn main() { // let input_buf=get_user_input();// println!('{}',input_buf); match send_post().await { Ok(res)=>{ println!('{:#?}',res); let data:Vec
=serde_json::from_str(&res).map_err(|e| format!('Deserialization error: {e}'))?; // 修改此处 let completions:Vec =data.iter().map(|c| c.completion.clone()).collect(); println!('{:#?}',completions); } Err(e)=>{eprintln!('{:?}',e)} }
}
#[derive(Debug, Deserialize)] struct Completion{ #[serde(rename='completion')] completion:String, }
//获取用户键盘输入 fn _get_user_input() -> String { let mut input_buf = String::new(); let _input = io::stdin().read_line(&mut input_buf).expect('fail to get user input.'); input_buf }
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 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?
)
}
**代码解释:**
1. **引入必要的库:**
* `std::io`:用于获取用户输入
* `std::collections::HashMap`:用于构建请求体
* `std::fmt::format`:用于格式化错误信息
* `reqwest`:用于发送 HTTP 请求
* `serde`:用于序列化和反序列化 JSON 数据
* `serde_derive`:用于生成 `Deserialize` trait 的宏
2. **定义 `Completion` 结构体:**
* 该结构体用于解析 JSON 响应数据,包含 `completion` 字段
3. **定义 `_get_user_input` 函数:**
* 该函数用于获取用户从键盘输入的信息,但本例中没有使用
4. **定义 `send_post` 函数:**
* 该函数用于发送 POST 请求,并返回响应的字符串
* **构建请求头:** 使用 `HeaderMap` 构建请求头,设置 `User-Agent`、`referer` 和 `sec-ch-ua`
* **构建请求体:** 使用 `HashMap` 构建请求体,设置 `prompt` 字段为 `hello`
* **发送请求:** 使用 `reqwest::Client` 发送 POST 请求,设置请求头和请求体
* **获取响应:** 使用 `await?` 获取响应,并使用 `text()` 方法将响应内容转换为字符串
5. **主函数 `main`:**
* 使用 `tokio::main` 宏标记该函数为异步函数
* 调用 `send_post` 函数发送请求
* **解析响应:** 使用 `serde_json::from_str` 将响应字符串解析为 `Completion` 结构体,并处理解析错误
* **打印解析结果:** 将 `Completion` 结构体的 `completion` 字段打印出来
**注意:**
* 本示例中使用了 `await?` 运算符来处理异步操作,需要在 `main` 函数上使用 `#[tokio::main]` 宏标记为异步函数。
* 本示例中使用了 `serde_derive` 宏,需要在项目中添加 `serde` 和 `serde_derive` 的依赖。
* 本示例使用了 `reqwest` 库,需要在项目中添加 `reqwest` 的依赖。
* 示例中使用到的 API 接口 `https://free-api.cveoy.com/v3/completions` 是一个免费的 AI 代码补全 API 接口,可以根据请求的 `prompt` 字段生成代码建议。', 'content_en': '```rust
use std::{io, collections::HashMap};
use std::fmt::format;
use std::io::BufRead;
use reqwest::header::HeaderMap;
use serde::{Deserialize};
use serde_derive::Deserialize;
#[tokio::main]
async fn main() {
// let input_buf=get_user_input();
// println!('{}',input_buf);
match send_post().await {
Ok(res)=>{
println!('{:#?}',res);
let data:Vec<Completion>=serde_json::from_str(&res).map_err(|e| format!('Deserialization error: {e}'))?; // 修改此处
let completions:Vec<String>=data.iter().map(|c| c.completion.clone()).collect();
println!('{:#?}',completions);
}
Err(e)=>{eprintln!('{:?}',e)}
}
}
#[derive(Debug, Deserialize)]
struct Completion{
#[serde(rename='completion')]
completion:String,
}
//获取用户键盘输入
fn _get_user_input() -> String {
let mut input_buf = String::new();
let _input = io::stdin().read_line(&mut input_buf).expect('fail to get user input.');
input_buf
}
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 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?
)
}
Code Explanation:
-
Import Necessary Libraries:
std::io:for getting user inputstd::collections::HashMap:for building request bodystd::fmt::format:for formatting error messagesreqwest:for sending HTTP requestsserde:for serializing and deserializing JSON dataserde_derive:for generatingDeserializetrait macro
-
Define
CompletionStruct:- This struct is used to parse JSON response data, containing the
completionfield.
- This struct is used to parse JSON response data, containing the
-
Define
_get_user_inputFunction:- This function is for getting user input from the keyboard, but it's not used in this example.
-
Define
send_postFunction:- This function is for sending a POST request and returning the response as a string.
- Build Request Headers: Use
HeaderMapto build request headers, setUser-Agent,refererandsec-ch-ua. - Build Request Body: Use
HashMapto build the request body, set thepromptfield tohello. - Send Request: Use
reqwest::Clientto send a POST request, set request headers and body. - Get Response: Use
await?to get the response and use thetext()method to convert the response content to a string.
-
Main Function
main:- Mark this function as an asynchronous function using the
#[tokio::main]macro. - Call the
send_postfunction to send a request. - Parse Response: Use
serde_json::from_strto parse the response string into aCompletionstruct and handle parsing errors. - Print Parsing Results: Print the
completionfield of theCompletionstruct.
- Mark this function as an asynchronous function using the
Note:
- This example uses the
await?operator to handle asynchronous operations, which requires themainfunction to be marked as an asynchronous function using the#[tokio::main]macro. - This example uses the
serde_derivemacro, which requires addingserdeandserde_derivedependencies to the project. - This example uses the
reqwestlibrary, which requires adding thereqwestdependency to the project. - The API interface used in the example,
https://free-api.cveoy.com/v3/completions, is a free AI code completion API interface that can generate code suggestions based on thepromptfield of the request.
原文地址: https://www.cveoy.top/t/topic/lBOR 著作权归作者所有。请勿转载和采集!