使用gzip/deflate压缩的简单HTTP请求



我正在努力找出如何轻松发送HTTP/HTTPS请求以及处理gzip/delate压缩响应和cookie的最佳方式。

我发现最好的是https://github.com/mikeal/request它处理除压缩之外的所有。有没有一个模块或方法可以满足我的所有要求?

如果没有,我可以以某种方式将request和zlib结合起来吗?我试图将zlib和http.ServerRequest结合起来,但失败得很惨。

对于最近遇到这种情况的人,请求库现在支持开箱即用的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。传入消息对象,该对象可能包含压缩数据。请参阅下面的示例。

注意:截至2019年,请求内置了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

下面是一个使用枪压缩响应的工作示例

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

查看http://nodejs.org/docs/v0.6.0/api/zlib.html#examples

zlib现在已内置到node中。

查看源代码内部-必须在请求库本身上设置gzip参数,gzip才能工作。不确定这是否是故意的,但这是当前的实现。不需要额外的标题。

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

这里的所有答案都不起作用,我正在返回原始字节,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);

最新更新