rust - 为什么 reqwest 不返回此请求中的内容长度?
问题描述
我很困惑为什么我没有从以下函数中获取任何内容,该函数使用reqwest
:
fn try_get() {
let wc = reqwest::Client::new();
wc.get("https://httpbin.org/json").send().map(|res| {
println!("{:?}", res);
println!("length {:?}", res.content_length());
});
}
我期待这个函数显示响应对象,然后给我内容长度。它做了第一个但不是第二个:
Response { url: "https://httpbin.org/json", status: 200, headers: {"access-control-allow-credentials": "true", "access-control-allow-origin": "*", "connection": "keep-alive", "content-type": "application/json", "date": "Tue, 26 Feb 2019 00:52:47 GMT", "server": "nginx"} }
length None
这很令人困惑,因为如果我使用 cURL 访问同一个端点,它会给我一个预期的主体:
$ curl -i https://httpbin.org/json
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Content-Type: application/json
Date: Tue, 26 Feb 2019 00:54:57 GMT
Server: nginx
Content-Length: 429
Connection: keep-alive
{
"slideshow": {
"author": "Yours Truly",
"date": "date of publication",
"slides": [
{
"title": "Wake up to WonderWidgets!",
"type": "all"
},
{
"items": [
"Why <em>WonderWidgets</em> are great",
"Who <em>buys</em> WonderWidgets"
],
"title": "Overview",
"type": "all"
}
],
"title": "Sample Slide Show"
}
}
我的函数没有为我提供内容长度有什么问题?
解决方案
的reqwest
文档content_length()
始终是一个很好的起点。它指出
获取响应的内容长度(如果已知)。
可能不知道的原因:
- 服务器没有发送内容长度标头。
- 响应被压缩并自动解码(从而改变实际解码长度)。
查看您的示例curl
输出,它包含Content-Length: 429
第一个案例。所以现在让我们尝试禁用 gzip:
let client = reqwest::Client::builder()
.gzip(false)
.build()
.unwrap();
client.get("https://httpbin.org/json").send().map(|res| {
println!("{:?}", res);
println!("length {:?}", res.content_length());
});
哪些日志
length Some(429)
所以第二种情况就是问题所在。默认情况下,reqwest
似乎会自动处理 gzip 压缩的内容,而curl
并非如此。
HTTP 标头完全是可选的Content-Length
,因此通常依赖它的存在是错误的。您应该使用其他 API 从请求中读取数据reqwest
,然后计算数据本身的长度。例如,您可以使用.text()
let wc = reqwest::Client::new();
let mut response = wc.get("https://httpbin.org/json").send().unwrap();
let text = response.text().unwrap();
println!("text: {} => {}", text.len(), text);
同样,对于二进制数据,您可以使用.copy_to()
:
let wc = reqwest::Client::new();
let mut response = wc.get("https://httpbin.org/json").send().unwrap();
let mut data = vec![];
response.copy_to(&mut data).unwrap();
println!("data: {}", data.len());
推荐阅读
- html - 由于路由错误,刷新 Angular 页面会破坏网页
- sql - 使用多个条件 AND / OR 的性能
- javascript - 为什么 JavaScript Promise Catch 没有被触发
- html - web-publisher 如何阻止 Amazon Affiliate DEEP-LINKS 在 Amazon App 中打开
- python - 如何根据标签绘制具有不同颜色的配对数据
- java - 在 RecyclerView 中的扩展项目上使用带有 ChangeBounds 的 TransitionManager 与 layout_height: match_constraint 结合使用会产生奇怪的视觉效果
- c++ - C ++中int的最小大小是多少?
- tizen - 如何在三星智能电视的 Tizen 浏览器中调试代码
- c++ - 为什么我不能使用实现 operator unsigned int() 的类作为 Visual C++ 32 位中的数组索引?
- python - Python v/s MATLAB 中的 SVD 命令