Ale*_*own 6 rest gzip get r rcurl
我正在构建客户端到RESTful API.一些链接让我从服务器下载附件(文件),在最好的情况下,这些是.txt.我只提到RESTful部分,因为它意味着我必须发送一些标题和每个帖子的潜在正文 - 标准的R'文件名'= URL逻辑将不起作用.
有时人们将许多txts捆绑成拉链.这些都很尴尬,因为我不知道它们包含了什么,直到我下载了很多它们.
目前,我正在解包这些,解压缩文件(添加.gz扩展名)并重新上传它们.然后可以将它们编入索引并下载.
我正在使用Hadley的可爱httr包,但我看不到一种优雅的解压缩gz文件的方法.
使用read.csv或类似文件时,任何带有gz结尾的文件都会自动解压缩(方便!).使用httr或curl时的等价物是什么?
content(GET("http://glimmer.rstudio.com/alexbbrown/gz/sample.txt.gz"))
[1] 1f 8b 08 08 4e 9e 9b 51 00 03 73 ...
看起来不错,一个带有正确标头的压缩字节流(1f 8b).现在我需要文本内容,所以我尝试使用memDecompress,它说应该这样做:
memDecompress(content(GET("http://glimmer.rstudio.com/alexbbrown/gz/sample.txt.gz")),type="gzip")
Error in memDecompress(content(GET("http://glimmer.rstudio.com/alexbbrown/gz/sample.txt.gz")),  : 
  internal error -3 in memDecompress(2)
这里有什么合适的解决方案?
另外,有没有办法让R拉出远程.zip文件的INDEX而不下载所有文件?
以下作品,但似乎有点复杂:
> scan(gzcon(rawConnection(content(GET("http://glimmer.rstudio.com/alexbbrown/gz/sample.txt.gz")))),"",,,"\n")
Read 1 item
[1] "These are not the droids you are looking for"
您可以添加解析器来处理 mime 类型。看看?content还有线You can add new parsers by adding appropriately functions to httr:::parser 
ls(httr:::parsers)
#[1] "application/json"                  "application/x-www-form-urlencoded" #"image/jpeg"                       
#[4] "image/png"                         "text/html"                         #"text/plain"                       
#[7] "text/xml"     
我们可以添加一个来处理gz内容。目前我没有比您给出的更好的答案,因此您可以合并您的功能。
assign("application/octet-stream", function(x, ...) {scan(gzcon(rawConnection(x)),"",,,"\n")},envir = httr:::parsers)
content(GET("http://glimmer.rstudio.com/alexbbrown/gz/sample.txt.gz"), as = "parsed")
Read 1 item
[1] "These are not the droids you are looking for"
> 
编辑:我拼凑了一个替代方案:
assign("application/octet-stream", function(x, ...) {f <- tempfile(); writeBin(x,f);untar(f);readLines(f, warn = FALSE)},envir = httr:::parsers)
content(GET("http://glimmer.rstudio.com/alexbbrown/gz/sample.txt.gz"), as = "parsed")
#[1] "These are not the droids you are looking for"
关于列出存档中的文件,也许您可以稍微调整一下功能。如果我们尝试获取httr源文件。他们有一个 mime 类型“application/x-gzip”
assign("application/x-gzip", function(x, ...) {
    f <- tempfile(); 
    writeBin(x,f); 
    if(!is.null(list(...)$list)){
        if(list(...)$list){
            return(untar(f, list = TRUE))
        }else{
            untar(f, ...);
            readLines(f)
        }
    }else{
        untar(f, ...);
        readLines(f)
    }
}, envir = httr:::parsers)
content(GET("http://cran.r-project.org/src/contrib/httr_0.2.tar.gz"), as = "parsed", list = TRUE)
# > head(content(GET("http://cran.r-project.org/src/contrib/httr_0.2.tar.gz"), as = "parsed", list = TRUE))
#[1] "httr/"                 "httr/MD5"              "httr/tests/"          
#[4] "httr/tests/test-all.R" "httr/README.md"        "httr/R/"