Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将cookies与RCurl一起使用?_R_Curl_Rcurl - Fatal编程技术网

如何将cookies与RCurl一起使用?

如何将cookies与RCurl一起使用?,r,curl,rcurl,R,Curl,Rcurl,我试图编写一个R包,通过RESTAPI访问一些数据。但是,API不使用http身份验证,而是依赖cookie来保存会话的凭据 本质上,我想用两个R函数替换bash脚本中的以下两行:一个用于执行登录并存储会话cookie,另一个用于获取数据 curl -X POST -c cookies.txt -d"username=xxx&password=yyy" http://api.my.url/login curl -b cookies.txt

我试图编写一个R包,通过RESTAPI访问一些数据。但是,API不使用http身份验证,而是依赖cookie来保存会话的凭据

本质上,我想用两个R函数替换bash脚本中的以下两行:一个用于执行登录并存储会话cookie,另一个用于获取数据

curl -X POST -c cookies.txt -d"username=xxx&password=yyy" http://api.my.url/login
curl         -b cookies.txt                               http://api.my.url/data
我显然不明白RCurl是如何与curl选项一起工作的。我目前的剧本是:

library(RCurl)
curl <- getCurlHandle()
curlSetOpt(cookiejar='cookies.txt', curl=curl)
postForm("http://api.my.url/login", username='xxx', password='yyy', curl=curl)
getURL('http://api.my.url/data", curl=curl)
库(RCurl)

卷曲我的不好。尼尔·里克特向我指出——这更好地解释了
cookiefile
cookiejar
之间的区别。问题中的示例脚本确实有效。但它只在不再使用时将文件写入磁盘

通常不需要创建cookie文件,除非您想研究cookie

有鉴于此,实际上,web服务器使用代理数据、重定向和隐藏post数据,但这应该有帮助:

library(RCurl)

#Set your browsing links 
loginurl = "http://api.my.url/login"
dataurl  = "http://api.my.url/data"

#Set user account data and agent
pars=list(
     username="xxx"
     password="yyy"
)
agent="Mozilla/5.0" #or whatever 

#Set RCurl pars
curl = getCurlHandle()
curlSetOpt(cookiejar="cookies.txt",  useragent = agent, followlocation = TRUE, curl=curl)
#Also if you do not need to read the cookies. 
#curlSetOpt(  cookiejar="", useragent = agent, followlocation = TRUE, curl=curl)

#Post login form
html=postForm(loginurl, .params = pars, curl=curl)

#Go wherever you want
html=getURL(dataurl, curl=curl)

#Start parsing your page
matchref=gregexpr("... my regexp ...", html)

#... .... ...

#Clean up. This will also print the cookie file
rm(curl)
gc()
重要的
除了用户名和密码之外,经常会有隐藏的帖子数据。要捕获它,您可能需要(例如在Chrome中)使用
Developer tools
(Ctrl-Shift I)->
网络选项卡
,以显示帖子字段名称和值

你真是个天才+这是一个非常棒的解决方案