问题
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