Rust异步编程:使用reqwest发送POST请求并处理错误
Rust异步编程:使用reqwest发送POST请求并处理错误
以下代码展示了如何使用Rust中的async/await语法和reqwest库发送POST请求,并使用if let语句处理请求过程中可能出现的错误。
async fn main() {
// let input_buf=get_user_input();
// println!("{}",input_buf);
if let Ok(res) = send_post().await {
println!("result is :{:?}", res);
} else {
println!("hello");
}
}
//获取用户键盘输入
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<serde_json::Value, 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?
.json::<serde_json::Value>()
.await?)
}
解释:
-
send_post()函数尝试发送一个POST请求,如果请求成功,则返回一个Ok结果,其中包含响应数据的JSON解析结果;如果请求失败,则返回一个Err结果,其中包含reqwest::Error类型的错误信息。 -
main()函数使用if let Ok(res) = send_post().await语句来判断send_post()函数的执行结果。如果返回的是Ok,则打印响应结果;如果返回的是Err,则执行else语句,并打印"hello"。
如何定位错误:
如果send_post()函数出现错误,你可以在else语句中打印错误信息,以便排查问题。例如:
async fn main() {
// let input_buf=get_user_input();
// println!("{}",input_buf);
if let Ok(res) = send_post().await {
println!("result is :{:?}", res);
} else {
if let Err(err) = send_post().await {
println!("Error: {:?}", err);
}
}
}
通过打印错误信息,你可以了解到导致请求失败的具体原因,并根据错误信息进行调试和修复。
原文地址: https://www.cveoy.top/t/topic/lBMf 著作权归作者所有。请勿转载和采集!