在 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
与
type 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
我可以手动读取 cookie 行,例如:
Set-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"))
我收到类似的回复:
Response [http://www.example.com/error]
Status: 411
Content-type: text/html
<h1>Length Required</h1>
总的来说,我知道 411 错误,我可以尝试修复请求;但我没有在 cURL 中得到它,所以我在 POST 命令上做错了。
你能帮我把我的 cURL 命令翻译成 RCurl 和/或 httr 吗?
最佳答案
httr
如对 http://httpbin.org 的两次调用所示,自动保留对同一站点的调用之间的 cookie。
GET("http://httpbin.org/cookies/set?a=1")
# Response [http://httpbin.org/cookies]
# Status: 200
# Content-type: application/json
# {
# "cookies": {
# "a": "1"
# }
# }
GET("http://httpbin.org/cookies")
# Response [http://httpbin.org/cookies]
# Status: 200
# Content-type: application/json
# {
# "cookies": {
# "a": "1"
# }
# }
也许问题在于您将数据发送为
application/x-www-form-urlencoded
,但 httr 中的默认值是 multipart/form-data
,所以使用 multipart = FALSE
在您的 POST
称呼。
关于r - 使用带有 cURL、RCurl 和 httr 的 cookie 发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15000815/