How to make a POST request with header and data options in R using httr::POST?

给你一囗甜甜゛ 提交于 2019-12-04 06:44:12

问题


I am trying make a POST request with data and header information using httr::POST. I can see how to make a POST request, but I am unable to get it to work with curl's data (-d) and header (-H) options.

This works perfectly in my terminal (obviously with different data/api, but exactly the same format)

curl -H "Accept: application/json" -H "Content-type: application/json" -d '{"name": "Fred", "age": "5"}' "http://www.my-api.com"

Question

How can the above POST request be made (with headers and data) using httr::POST ?

What I've tried so far

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)

I get

Error: Bad Request (HTTP 400).

Inspecting r further

r
Response ["http://www.my-api.com"]
  Date: 2019-07-09 17:51
  Status: 400
  Content-Type: text/html; charset=UTF-8
<EMPTY BODY>

回答1:


You could try this; with content type and headers added:

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


来源:https://stackoverflow.com/questions/56958500/how-to-make-a-post-request-with-header-and-data-options-in-r-using-httrpost

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!