通过 gzip/deflate 压缩轻松实现 HTTP 请求

发布于 2024-12-27 09:34:02 字数 303 浏览 2 评论 0原文

我试图找出如何轻松发送 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

遮云壑 2025-01-03 09:34:02

对于最近遇到这个问题的人来说,请求库现在支持开箱即用的 gzip 解压缩。使用方式如下:

request(
    { method: 'GET'
    , uri: 'http://www.google.com'
    , gzip: true
    }
  , function (error, response, body) {
      // body is the decompressed response body
      console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
      console.log('the decoded data is: ' + body)
    }
  )

来自github自述文件https://github.com/request/request

gzip - 如果为 true,则添加 Accept-Encoding 标头以请求压缩
来自服务器的内容编码(如果尚未存在)并解码
响应中支持的内容编码。注:自动解码
响应内容的处理是对通过返回的主体数据执行的
请求(通过请求流并传递给回调
函数),但不在响应流上执行(可从
响应事件),这是未修改的 http.IncomingMessage
可能包含压缩数据的对象。请参阅下面的示例。

For anyone coming across this in recent times, the request library supports gzip decompression out of the box now. Use as follows:

request(
    { method: 'GET'
    , uri: 'http://www.google.com'
    , gzip: true
    }
  , function (error, response, body) {
      // body is the decompressed response body
      console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
      console.log('the decoded data is: ' + body)
    }
  )

From the github readme https://github.com/request/request

gzip - If true, add an Accept-Encoding header to request compressed
content encodings from the server (if not already present) and decode
supported content encodings in the response. Note: Automatic decoding
of the response content is performed on the body data returned through
request (both through the request stream and passed to the callback
function) but is not performed on the response stream (available from
the response event) which is the unmodified http.IncomingMessage
object which may contain compressed data. See example below.

在你怀里撒娇 2025-01-03 09:34:02

注意:从 2019 年开始,request 内置了 gzip 解压缩功能。您仍然可以使用以下方法手动解压缩请求。

可以简单地将 requestzlib 结合起来代码> 与流。

下面是一个示例,假设您有一个服务器正在侦听端口 8000 :

var request = require('request'), zlib = require('zlib');

var headers = {
    'Accept-Encoding': 'gzip'
};

request({url:'http://localhost:8000/', 'headers': headers})
    .pipe(zlib.createGunzip()) // unzip
    .pipe(process.stdout); // do whatever you want with the stream

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 and zlib with streams.

Here is an example assuming you have a server listening on port 8000 :

var request = require('request'), zlib = require('zlib');

var headers = {
    'Accept-Encoding': 'gzip'
};

request({url:'http://localhost:8000/', 'headers': headers})
    .pipe(zlib.createGunzip()) // unzip
    .pipe(process.stdout); // do whatever you want with the stream
小糖芽 2025-01-03 09:34:02

这是一个压缩响应的工作示例

function gunzipJSON(response){

    var gunzip = zlib.createGunzip();
    var json = "";

    gunzip.on('data', function(data){
        json += data.toString();
    });

    gunzip.on('end', function(){
        parseJSON(json);
    });

    response.pipe(gunzip);
}

完整代码: https://gist.github.com/0xPr0xy/5002984< /a>

Here's a working example that gunzips the response

function gunzipJSON(response){

    var gunzip = zlib.createGunzip();
    var json = "";

    gunzip.on('data', function(data){
        json += data.toString();
    });

    gunzip.on('end', function(){
        parseJSON(json);
    });

    response.pipe(gunzip);
}

Full code: https://gist.github.com/0xPr0xy/5002984

在你怀里撒娇 2025-01-03 09:34:02

Check out the examples at http://nodejs.org/docs/v0.6.0/api/zlib.html#examples

zlib is now built into node.

梦醒灬来后我 2025-01-03 09:34:02

查看 源代码 - 您必须设置 gzip 参数在请求库本身上,以便 gzip 工作。不确定这是有意还是无意,但这是当前的实现。不需要额外的标头。

var request = require('request');
request.gzip = true;
request({url: 'https://...'},  // use encoding:null for buffer instead of UTF8
    function(error, response, body) { ... }
);

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.

var request = require('request');
request.gzip = true;
request({url: 'https://...'},  // use encoding:null for buffer instead of UTF8
    function(error, response, body) { ... }
);
や莫失莫忘 2025-01-03 09:34:02

这里的所有答案都不起作用,我取回了原始字节,并且 gzip 标志也不起作用。事实证明,您需要将编码设置为 null 以防止请求将响应转换为 utf-8 编码,而是保留二进制响应。

const request = require("request-promise-native");
const zlib = require("zlib");

const url = getURL("index.txt");
const dataByteBuffer = await request(url, { encoding: null });
const dataString = zlib.gunzipSync(response);

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 to null to prevent requests from transforming the response to utf-8 encoding and instead keeps the binary response.

const request = require("request-promise-native");
const zlib = require("zlib");

const url = getURL("index.txt");
const dataByteBuffer = await request(url, { encoding: null });
const dataString = zlib.gunzipSync(response);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文