我需要使用R程序发送HTTPS POST请求,以将JSON数据上传到Splunk。
我正在探索curl库,但是在通过HTTPS执行简单的GET调用时遇到错误。这让我觉得curl不能为HTTPS请求提供支持..
Rstudio:版本1.0.136 R:3.3.2 卷曲:版本2.3
============================================== 示例代码:
library(curl)
request <- curl_fetch_memory("https://httpbin.org/get")
Error : Error in curl_fetch_memory("https://httpbin.org/get") :
Failure when receiving data from the peer
however, i the similar GET request for http endpoint works pretty fine.
i.e. request <- curl_fetch_memory("http://httpbin.org/get")
答案 0 :(得分:1)
最后能够使https调用在R中工作。
如假设的那样,公司代理问题影响了https流量,而不是http。
以下是我执行的步骤..感谢帖子:http://blog.csdn.net/wangishero/article/details/50859670
a) in Rstudio, go to "Tools --> Global Options --> Packages " . Uncheck the option "User Internet Explorer library/proxy for http"
b) # load httr library
library(httr)
c) # set proxy configuration
set_config(use_proxy(url="<corporate proxy>",port=<port>, username="<username>", password="<ur pwd>"))
d) # this is to prevent SSL warning
set_config( config( ssl_verifypeer = 0L ) )
现在我可以毫无问题地执行Https请求。
答案 1 :(得分:0)
httr
库可用于GETting和POST到API端点
library(httr)
httr::GET("https://httpbin.org/get")
# Response [https://httpbin.org/get]
# Date: 2017-06-27 05:24
# Status: 200
# Content-Type: application/json
# Size: 326 B
# {
# "args": {},
# "headers": {
# "Accept": "application/json, text/xml, application/xml, */*",
# "Accept-Encoding": "gzip, deflate",
# "Connection": "close",
# "Host": "httpbin.org",
# "User-Agent": "libcurl/7.51.0 r-curl/2.5 httr/1.2.1"
# },
# "origin": "45.126.44.231",
# ...
同样,POST有一个httr::POST
函数。
示例POST看起来像
requestBody <- paste0('{
"foo" : [
{"id" : "myId",
"values" : {"a" : "b"}
}
]
}')
res <- httr::POST(url = url,
httr::add_headers('Content-Type' = 'application/json'),
httr::add_headers('Accept' = 'application/json'),
httr::add_headers('X-Application-Id' = appId),
httr::add_headers('X-Api-Key' = apiKey),
body = requestBody,
encode = "json")