带有httr的R POST API请求返回了错误的请求

时间:2019-08-26 18:44:50

标签: r api post rcurl httr

想通过R中的POST包中的curl来实现以下httr请求

curl 'https://api.openfigi.com/v2/mapping' \
--request POST \
--header 'Content-Type: application/json' \
--data '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]'

基于此Git issue,我尝试了:

library(jsonlite)
library(rjson)
#> 
#> Attaching package: 'rjson'
#> The following objects are masked from 'package:jsonlite':
#> 
#>     fromJSON, toJSON
library(httr)

url = 'https://api.openfigi.com/v2/mapping'

body1 = list(
  idType = jsonlite::unbox('ID_WERTPAPIER'),
  idValue = jsonlite::unbox('851399'),
  exchCode = jsonlite::unbox('US')
)
r = httr::POST(url, body = body1, encode = 'json', verbose())

body2 = rjson::toJSON(list(
  idType = "ID_WERTPAPIER",
  idValue = "851399",
  exchCode = "US"
))

r = httr::POST(url, body = body2, encode = "form", verbose())

reprex package(v0.3.0)于2019-08-26创建

但这两个都是不好的请求。

1 个答案:

答案 0 :(得分:1)

如果仅平移卷曲,以下内容似乎可以工作。够了吗?

require(httr)

headers = c(
  `Content-Type` = 'application/json'
)

data = '[{"idType":"ID_WERTPAPIER","idValue":"851399","exchCode":"US"}]'

r <- httr::POST(url = 'https://api.openfigi.com/v2/mapping', httr::add_headers(.headers=headers), body = data)
print(r$status_code)