通过 gzip/deflate 压缩轻松实现 HTTP 请求
我试图找出如何轻松发送 HTTP/HTTPS 请求以及处理 gzip/deflate 压缩响应和 cookie 的最佳方法。
我发现最好的是 https://github.com/mikeal/request 它可以处理除压缩。是否有一个模块或方法可以完成我要求的一切?
如果没有,我可以以某种方式将 request 和 zlib 结合起来吗?我尝试将 zlib 和 http.ServerRequest 结合起来,但失败得很惨。
I'm trying to figure out how the best way to easily send HTTP/HTTPS requests and to handle gzip/deflate compressed responses along with cookies.
The best I found was https://github.com/mikeal/request which handles everything except compression. Is there a module or method that will do everything I ask?
If not, can I combine request and zlib in some manner? I tried to combine zlib and http.ServerRequest
, and it failed miserably.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
对于最近遇到这个问题的人来说,请求库现在支持开箱即用的 gzip 解压缩。使用方式如下:
来自github自述文件https://github.com/request/request
For anyone coming across this in recent times, the request library supports gzip decompression out of the box now. Use as follows:
From the github readme https://github.com/request/request
注意:从 2019 年开始,request 内置了 gzip 解压缩功能。您仍然可以使用以下方法手动解压缩请求。您
可以简单地将
request
和zlib
结合起来代码> 与流。下面是一个示例,假设您有一个服务器正在侦听端口 8000 :
Note: as of 2019, request has gzip decompression built in. You can still decompress requests manually using the below method.
You can simply combine
request
andzlib
with streams.Here is an example assuming you have a server listening on port 8000 :
这是一个压缩响应的工作示例
完整代码: https://gist.github.com/0xPr0xy/5002984< /a>
Here's a working example that gunzips the response
Full code: https://gist.github.com/0xPr0xy/5002984
查看 http://nodejs.org/docs/v0 中的示例。 6.0/api/zlib.html#examples
zlib 现已内置到 Node 中。
Check out the examples at http://nodejs.org/docs/v0.6.0/api/zlib.html#examples
zlib is now built into node.
查看 源代码 - 您必须设置
gzip
参数在请求库本身上,以便 gzip 工作。不确定这是有意还是无意,但这是当前的实现。不需要额外的标头。Looking inside the source code - you must set the
gzip
param on the request lib itself for gzip to work. Not sure if this was intentional or not, but this is the current implementation. No extra headers are needed.这里的所有答案都不起作用,我取回了原始字节,并且
gzip
标志也不起作用。事实证明,您需要将编码设置为null
以防止请求将响应转换为 utf-8 编码,而是保留二进制响应。All the answers here did not work and I was getting raw bytes back instead and the
gzip
flag was not working either. As it turns out you need to set the encoding tonull
to prevent requests from transforming the response to utf-8 encoding and instead keeps the binary response.