【问题标题】:R POST API request with httr returns bad requests带有 httr 的 R POST API 请求返回错误请求
【发布时间】:2019-08-26 18:44:50
【问题描述】:

希望使用 R 中的 httr 包实现以下 POST 请求和 curl

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 年 8 月 26 日创建

但两者都是错误的请求。

【问题讨论】:

    标签: r api post rcurl httr


    【解决方案1】:

    如果您只翻译 curl,以下内容似乎有效。够了吗?

    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)
    

    【讨论】:

    • 如果我可能会问:您知道我们为什么不必按照文档?POST 中的建议使用encode = "raw" 吗?
    • @ThanksGuys docu ?POST 是什么?
    • 在控制台(在 R 中)输入 ?POST 时出现的文档。实际上我应该提供直接链接:rdocumentation.org/packages/httr/versions/1.4.1/topics/POST, sry.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多