r - 发送数据时使用POST下载R中的文件

标签 r post curl http-post httr

我尝试下载一个文件,从我需要同时发送数据的服务器获取它。在命令行上使用 curl 可以正常工作:

curl "https://www.ishares.com/us/product-screener-download.dl" --data "productView=ishares&portfolios=239561-239855"

不幸的是,我没有让它与 R 一起工作。我尝试使用 download.file、download.file 和 libcurl、curl_download 和 httr。 (带有 curl 或 wget 的 download.file 不起作用,因为我在窗口机器上。)

我尝试过但对 curl 不起作用的内容:
library("curl")
handle <- new_handle()
handle_setopt(handle, customrequest = "POST")
handle_setform(handle, productView="ishares",portfolios="239561-239855")
curl_download("https://www.ishares.com/us/products/etf-product-list", "./data/ishares-us-etf.xls", handle=handle)

我尝试过但对 httr 不起作用的内容:
library(httr)
POST("https://www.ishares.com/us/products/etf-product-list", body = list(productView="ishares",portfolios="239561-239855"))

最佳答案

所以你应该使用正确的 URL 和 encode = "form"httr::POST() .
httr基于@leo 答案的解决方案:

library(httr)
POST("https://www.ishares.com/us/product-screener-download.dl",
     body = list(productView = "ishares", portfolios = "239561-239855"),
     encode = "form", write_disk("/tmp/ishares-us-etf.xls"))
#> Response [https://www.ishares.com/us/product-screener-download.dl]
#>   Date: 2016-02-08 06:52
#>   Status: 200
#>   Content-Type: application/vnd.ms-excel;charset=UTF-8
#>   Size: 13.6 kB
#> <ON DISK>  /tmp/ishares-us-etf.xls
head(readLines(file_path), 5)
#>   [1] "<?xml version=\"1.0\"?>"
#>   [2] "<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">"
#>   [3] "<Styles>"                          
#>   [4] "<Style ss:ID=\"Default\">"
#>   [5] "<Alignment Horizontal=\"Left\"/>"

关于r - 发送数据时使用POST下载R中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34864162/

相关文章:

c++ - 如何将多个对象从 Rcpp 返回到 R?

r - 使用 R Shiny 进行多元线性回归(SelectInput --> multiple=TRUE)

ajax - 浏览器是否允许跨域请求为 "sent"?

curl - 如何从没有附加内容 URL 的下载按钮获取或 curl ?

linux - 我如何发布包含符号的多部分/表单数据

c++ - 读取 header ,CURL

r - 如何修复R中的 "failed to load cairo DLL"?

r - 如何使用字符对象重命名带有 dplyr 的列

swift - 使用 Swift 将图像上传到服务器时出错

php - 发布具有相同名称属性的表单字段