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?
    )



}


代码解释:

  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-Agentreferersec-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 宏,需要在项目中添加 serdeserde_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:

  1. Import Necessary Libraries:

    • std::io:for getting user input
    • std::collections::HashMap:for building request body
    • std::fmt::format:for formatting error messages
    • reqwest:for sending HTTP requests
    • serde:for serializing and deserializing JSON data
    • serde_derive:for generating Deserialize trait macro
  2. Define Completion Struct:

    • This struct is used to parse JSON response data, containing the completion field.
  3. Define _get_user_input Function:

    • This function is for getting user input from the keyboard, but it's not used in this example.
  4. Define send_post Function:

    • This function is for sending a POST request and returning the response as a string.
    • Build Request Headers: Use HeaderMap to build request headers, set User-Agent, referer and sec-ch-ua.
    • Build Request Body: Use HashMap to build the request body, set the prompt field to hello.
    • Send Request: Use reqwest::Client to send a POST request, set request headers and body.
    • Get Response: Use await? to get the response and use the text() method to convert the response content to a string.
  5. Main Function main:

    • Mark this function as an asynchronous function using the #[tokio::main] macro.
    • Call the send_post function to send a request.
    • Parse Response: Use serde_json::from_str to parse the response string into a Completion struct and handle parsing errors.
    • Print Parsing Results: Print the completion field of the Completion struct.

Note:

  • This example uses the await? operator to handle asynchronous operations, which requires the main function to be marked as an asynchronous function using the #[tokio::main] macro.
  • This example uses the serde_derive macro, which requires adding serde and serde_derive dependencies to the project.
  • This example uses the reqwest library, which requires adding the reqwest dependency 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 the prompt field of the request.
Rust 使用 reqwest 发送 POST 请求并解析 JSON 响应

原文地址: https://www.cveoy.top/t/topic/lBOR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录