首页 > 解决方案 > 使用 httr R 接受 gzip 编码

问题描述

我订阅了金融数据提供商 ORATS。软件工程师联系我,让我知道我的 GET() 请求超时。他说允许在我的 GET() 请求标头中进行 gzip 编码。SWE 不在 R 中编写代码,并已向我发送了一些 node.js 代码供我参考。

我认为 httr GET() 请求会自动将文件压缩为 gzip。

下面是 SWE 提供的 node.js 代码,后面是我当前的 R 代码,这些代码一直有效,直到我增加了从他们的 API 中提取的文件的大小(开始超时)。

const request = require('request');

const options = {
  url: 'https://api.orats.io/data/cores/general?include=earn',
  headers: {
  'Authorization' : 'your authorization token',
  'Accept-Encoding' : 'gzip'
  },
  gzip : true
};

request(options, function(err, response, body){
// Body is already uncompressed b/c the request library uncompresses it for you.
console.log(JSON.parse(body));
});


R code:
library(httr)
x = GET(url, add_headers(Authorization = token))
y = rawToChar(x$content)

我希望此代码请求 gzip 文件。谢谢你。

标签: rnode.jsjsonhttr

解决方案


将同一Accept-Encoding行也添加到 httr GET 请求中:

library(httr)
x = GET(url, add_headers(.headers = c('Authorization'= token,
                                      'Accept-Encoding' = 'gzip, deflate')))

请注意,httr 会自动解压缩响应


推荐阅读