Rust 如何在reqwest中的解码失败错误中获取响应正文?
目前我只能得到错误消息,它是Rust 如何在reqwest中的解码失败错误中获取响应正文?,rust,actix-web,rust-actix,Rust,Actix Web,Rust Actix,目前我只能得到错误消息,它是错误解码响应体:第1行第1列的预期值 显然,错误的原因是httpbin.org正在返回HTML。我想知道如何将HTML返回给客户端 use actix_web::{get, App, Error, HttpResponse, HttpServer}; use reqwest; use std::collections::HashMap; #[get("/")] async fn index() -> Result<HttpRespon
错误解码响应体:第1行第1列的预期值
显然,错误的原因是httpbin.org
正在返回HTML。我想知道如何将HTML返回给客户端
use actix_web::{get, App, Error, HttpResponse, HttpServer};
use reqwest;
use std::collections::HashMap;
#[get("/")]
async fn index() -> Result<HttpResponse, Error> {
let res = reqwest::get("https://httpbin.org/404")
.await
.expect("Get request failed");
match res.json::<HashMap<String, String>>().await {
Ok(resp) => Ok(HttpResponse::Ok().json(resp)),
Err(e) => {
println!("{:?}", e);
Err(Error::from(HttpResponse::BadRequest().body(e.to_string())))
}
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(index))
.bind("127.0.0.1:8080")?
.run()
.await
}
使用actix_web:{get,App,Error,HttpResponse,HttpServer};
使用西部;
使用std::collections::HashMap;
#[获取(“/”)]
异步fn index()->结果{
让res=reqwest::get(“https://httpbin.org/404")
.等待
.expect(“获取请求失败”);
匹配res.json::()。等待{
Ok(resp)=>Ok(HttpResponse::Ok().json(resp)),
错误(e)=>{
println!(“{:?}”,e);
Err(Error::from(HttpResponse::BadRequest().body(e.to_string()))
}
}
}
#[actix_web::main]
异步fn main()->std::io::Result{
HttpServer::new(| | App::new().service(index))
.bind(“127.0.0.1:8080”)?
.run()
.等待
}
actix\u web
的响应::json
定义为:
pub async fn json<T: DeserializeOwned>(self) -> Result<T>
由于serde
不使用响应体,因此您只需保留response::bytes
的结果,就可以进一步使用它
尽管对我来说,如果您正在调用的端点可能不会将json返回到需要json的请求:
- 你应该调查一下原因?(TBF我不明白,当您专门查询站点的404时,为什么它会返回json?)
- 您应该能够检查响应的内容类型
pub async fn json<T: DeserializeOwned>(self) -> crate::Result<T> {
let full = self.bytes().await?;
serde_json::from_slice(&full).map_err(crate::error::decode)
}