r - 如何使用 httr::POST 在 R 中使用标头和数据选项发出 POST 请求?
问题描述
我正在尝试使用httr::POST
. 我可以看到如何发出 POST 请求,但我无法让它与 curl 的数据 ( -d
) 和标头 ( -H
) 选项一起使用。
这在我的终端中完美运行(显然使用不同的数据/api,但格式完全相同)
curl -H "Accept: application/json" -H "Content-type: application/json" -d '{"name": "Fred", "age": "5"}' "http://www.my-api.com"
问题
如何使用 发出上述 POST 请求(带有标头和数据)httr::POST
?
到目前为止我尝试过的
library(jsonlite)
my_data <- list(name="Fred", age="5") %>% toJSON
post_url <- "http://www.my-api.com"
r <- POST(post_url, body = my_data) # Data goes in body, I guess?
stop_for_status(r)
我明白了
Error: Bad Request (HTTP 400).
r
进一步检查
r
Response ["http://www.my-api.com"]
Date: 2019-07-09 17:51
Status: 400
Content-Type: text/html; charset=UTF-8
<EMPTY BODY>
解决方案
你可以试试这个;添加了内容类型和标题:
link <- "http://www.my-api.com"
df <- list(name="Fred", age="5")
httr::POST(url = link,
body = jsonlite::toJSON(df, pretty = T, auto_unbox = T),
httr::add_headers(`accept` = 'application/json'),
httr::content_type('application/json'))
推荐阅读
- git - Git - 我可以从更新的其他分支拉取提交到远程分支吗?
- c++ - AssaultCube Aimbot,我的偏航角和俯仰角值不起作用
- c# - 如何返回文本文件内容以及文件名?
- java - 基于程序功能的OOP封装?
- python - 从数据集中过滤非“群组”
- c# - 如何配置简单注入器以在上下文事务中实现命令处理程序模式
- docker - 在 nginx prometheus 导出器中提供但未定义的标志
- excel-formula - 当值不应为零时,引用隐藏表的 Excel 公式返回零
- rabbitmq - 如何将 RabbitListener 绑定到同一交换机上的多个路由键
- javascript - 如何使用nodejs fs将数据从一个目录复制到另一个目录?