目前,我只能收到错误消息error decoding response body: expected value at line 1 column 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
的Response::json
定义为:
pub async fn json<T: DeserializeOwned>(self) -> Result<T>
由于它按值获取self
,因此消耗了响应,因此无法访问它。因此,为了保持对响应主体的访问,您需要自己对它进行反序列化,以确保仍然可以访问并且不使用响应主体。
这很容易,因为
Response::json
是a very short helper: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)
}
由于serde
不会占用响应主体,因此您所要做的就是保留Response::bytes
的结果,然后就可以进一步使用它了。虽然对我来说,如果您正在调用的端点可能将not-json返回到要求json的请求中:
关于rust - 如何在reqwest中获取“解码失败”错误中的响应正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64421538/