php - 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")
解决方案
这个:
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 示例代码。
推荐阅读
- javascript - Konva / Canvas 上未缩放的交互层
- amazon-web-services - 每个端点的 Lambda AWS 函数
- bash - 带有 Bash 的彩虹表
- mysql - 如何将 "_id": { "$oid": "5ec796a7868d607e00f4b18d" } 和 "time": 1590137305745 插入 mysql 表中?
- vba - VBA:如果单词表中的第一个单元格具有特定值,则执行操作,否则转到下一个表
- python - 刮掉两个未嵌套标签之间的所有内容
- javascript - 我的函数不想出现在我的渲染上我怎么知道渲染正在工作?
- python - 如何正确抓取 python 网站表?
- python - 是否有用于在 python 中提取不同且非空值的脚本?
- google-cloud-identity - Google Identity Platform 可用的 MFA 程序