PHP的卷曲过程成R

时间:2018-10-05 09:22:35

标签: php r curl httr

我在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")

2 个答案:

答案 0 :(得分:2)

此:

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示例代码。

答案 1 :(得分:1)

第三行的url变量中有一个错字,这是正确的代码:

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")