r - 使用带有 cURL、RCurl 和 httr 的 cookie 发布请求

标签 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

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/

相关文章:

r - 沿 x 轴具有完整数据和子集的 ggplot

减少行梯队形式

带有 cURL 的 Android NDK 包含错误

node.js - 如何在 Node.js 中进行不安全的 HTTPS 调用

curl - 如何为 curl Rust crate 启用 NTLM 支持?

c - 从 curl_easy_perform() 获取数据的 libcurl 问题

windows - 当我尝试在 Windows Server 2008 中上传二进制文件时,LibCURL 发送文件名而不是文件内容

r - 获取 S3 打印方法的对象名称失败

php - 使用 PHP 解析推送通知

r - 通过在另一个数据帧中查找来聚合数据帧