首页 > 解决方案 > php curl过程进入R

问题描述

我在php中得到了followig curl过程:

$ch = curl_init();
$url = "www.sample.com";

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8", "Accept:application/json, text/javascript, */*; d=0.2"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIE, 'auth_tkt=myToken; anotherArg=234');

$result = curl_exec($ch);
curl_close($ch);

现在,我必须在 R 中进行翻译并执行此操作。我尝试了以下操作,但是,我得到了状态 403,所以我猜标题或 cookie 设置不正确:

library(httr)
url <- "www.sample.com"
res <- GET(url, 
           add_headers(`Content-Type` = "application/json",
                       charset="utf-8",
                       Accept = c("application/json", "text/javascript", "*/*"),
                       d="0.2"),
           set_cookies(auth_tkt="myToken", anotherArg="234")

标签: phprcurlhttr

解决方案


这个:

httr::GET(
  url = "http://httpbin.org/",
  httr::set_cookies(
    auth_tkt = "myToken",
    anotherArg = 234L
  ),
  httr::content_type("application/json; charset=utf-8"),
  httr::accept("application/json, text/javascript, */*; d=0.2"),
  httr::verbose()
)

几乎与@Alberto发布的内容相同,只是它使用了一些额外httr的辅助函数并正确设置了值。我做到了,verbose()所以我可以显示发送的内容:

-> GET / HTTP/1.1
-> Host: httpbin.org
-> User-Agent: libcurl/7.54.0 r-curl/3.2 httr/1.3.1
-> Accept-Encoding: gzip, deflate
-> Cookie: auth_tkt=myToken;anotherArg=234
-> Content-Type: application/json; charset=utf-8
-> Accept: application/json, text/javascript, */*; d=0.2

@Alberto 的代码最终发送:

-> GET / HTTP/1.1
-> Host: httpbin.org
-> User-Agent: libcurl/7.54.0 r-curl/3.2 httr/1.3.1
-> Accept-Encoding: gzip, deflate
-> Cookie: auth_tkt=myToken;anotherArg=234
-> Accept: application/json, text/xml, application/xml, */*
-> Content-Type: application/json
-> charset: utf-8
-> Accept1: application/json
-> Accept2: text/javascript
-> Accept3: */*
-> d: 0.2

这并不完全模仿 PHP 示例代码。


推荐阅读