使用带有cURL、RCurl和httr的cookie发布请求
在Windows cURL中,我可以发布类似以下内容的web请求:使用带有cURL、RCurl和httr的cookie发布请求,r,curl,libcurl,rcurl,httr,R,Curl,Libcurl,Rcurl,Httr,在Windows cURL中,我可以发布类似以下内容的web请求: curl --dump-header cook.txt ^ --data "RURL=http=//www.example.com/r&user=bob&password=hello" ^ --user-agent "Mozilla/5.0" ^ http://www.example.com/login 使用键入cook.txt我会得到类似以下的响应: HTTP/1.1 302 Found
curl --dump-header cook.txt ^
--data "RURL=http=//www.example.com/r&user=bob&password=hello" ^
--user-agent "Mozilla/5.0" ^
http://www.example.com/login
使用键入cook.txt
我会得到类似以下的响应:
HTTP/1.1 302 Found
Date: Thu, ******
Server: Microsoft-IIS/6.0
SERVER: ******
X-Powered-By: ASP.NET
X-AspNet-Version: 1.1.4322
Location: ******
Set-Cookie: Cookie1=; domain=******; expires=****** ******
******
******
Cache-Control: private
Content-Type: text/html; charset=iso-8859-1
Content-Length: 189
Response [http://www.example.com/error]
Status: 411
Content-type: text/html
<h1>Length Required</h1>
我可以手动读取cookie行,比如:设置cookie:AuthCode=ABC…
(当然我可以编写脚本)。因此,我可以对后续请求使用AuthCode
我正试图用RCurl和/或httr在R中做同样的事情(仍然不知道哪一个更适合我的任务)
当我尝试时:
library(httr)
POST("http://www.example.com/login",
body= list(RURL="http=//www.example.com/r",
user="bob", password="hello"),
user_agent("Mozilla/5.0"))
我得到的回应与此类似:
HTTP/1.1 302 Found
Date: Thu, ******
Server: Microsoft-IIS/6.0
SERVER: ******
X-Powered-By: ASP.NET
X-AspNet-Version: 1.1.4322
Location: ******
Set-Cookie: Cookie1=; domain=******; expires=****** ******
******
******
Cache-Control: private
Content-Type: text/html; charset=iso-8859-1
Content-Length: 189
Response [http://www.example.com/error]
Status: 411
Content-type: text/html
<h1>Length Required</h1>
响应[http://www.example.com/error]
现状:411
内容类型:text/html
所需长度
总的来说,我知道411错误,我可以尝试修复请求;但是我没有把它卷起来,所以我在邮政指挥部做了一些错误的事情
您能帮助我将cURL命令转换为RCurl和/或httr吗?这里有一种方法可以创建post请求,保存并使用RCurl重新使用生成的cookie,例如,在需要身份验证时获取网页:
library(RCurl)
curl <- getCurlHandle()
curlSetOpt(cookiejar="/tmp/cookies.txt", curl=curl)
postForm("http://example.com/login", login="mylogin", passwd="mypasswd", curl=curl)
getURL("http://example.com/anotherpage", curl=curl)
库(RCurl)
curlhttr
自动在对同一站点的调用之间保留cookie,这两个调用说明了这一点
可能问题是您正在以application/x-www-form-urlencoded
的形式发送数据,但是httr中的默认值是multipart/form data
,因此在POST
调用中使用multipart=FALSE
。根据朱巴的建议,这里是一个有效的RCurl模板
该代码模拟浏览器行为,因为它:
在登录屏幕上检索Cookie并
在包含实际数据的以下页面请求中重用它们李>
+1它起作用了。在关闭线程之前,让我们看看是否有人想用httr发布一些东西。从我阅读的文档来看,我不需要设置CURLOPT_COOKIEJAR-这只是将它们写入磁盘。@hadley如果我不使用COOKIEJAR
,我就无法访问需要cookies的站点。如果不需要实际文件,可以使用curlSetOpt(cookiejar=“”,curl=curl)
。无论如何,即使您传递了一个文件,也不会保存任何内容,除非您发出rm(curl);gc()
。请提供一个可复制的示例-您没有提供有关如何处理身份验证的足够详细信息。httr(如果我没记错的话)应该会自动在对同一站点的调用之间保留cookies