【问题标题】:Translating CURL to R将 CURL 转换为 R
【发布时间】:2020-01-03 23:01:02
【问题描述】:

主要出于我自己的理解,您如何使用 RCurl 或 httr 将以下玩具 CURL 示例翻译成 R:

  curl -v -X POST \
    https://someurl/endpoint \
-H "Content-Type: application/json" \
-H 'X-Api-Key: abc123' \
-d '{"parameters": [ 1, "foo", "bar" ]}'

除了简单的 GET 请求之外,我发现这两个包都有些尴尬。

我试过了:

library(httr)
 POST("https://someurl/endpoint", authenticate("user", "passwrd"), 
body = '{"parameters": [ 1, "foo", "bar" ]}', content_type_json())

获得 400 状态。我的 Curl 版本完美运行。

也试过了:

POST("https://someurl/endpoint", add_headers('X-Api-Key: abc123'), 
body = '{"parameters": [ 1, "foo", "bar" ]}', content_type_json())

同时获得 400 状态。

我很确定问题在于设置标题。

【问题讨论】:

  • 好吧,一方面,我不能在标题的名称值对中使用破折号。
  • 您是否尝试将正文作为 R 列表传递body = list(parameters = list(1, "foo", "bar" ))
  • 是的,我试过了,但没有成功。我认为问题在于设置标题。例如,您将如何使用 add_headers 设置标题?
  • 你能分享实际的网址和参数吗?更容易调试。另外,如果您在标头中传递密钥,我想您不想通过 authenticate() 传递基本身份验证

标签: r curl httr


【解决方案1】:

在此网页中,您可以将 curl 转换为多种语言:https://curl.trillworks.com/#r

在这种情况下,在 R 中是:

require(httr)

headers = c(
  'Content-Type' = 'application/json',
  'X-Api-Key' = 'abc123'
)

data = '{"parameters": [ 1, "foo", "bar" ]}'

res <- httr::POST(url = 'https://someurl/endpoint', httr::add_headers(.headers=headers), body = data)

【讨论】:

    【解决方案2】:

    您可以使用 httpbin.org 进行测试。试试:

    curl -v -X POST \
        https://httpbin.org/post \
    -H "Content-Type: application/json" \
    -H 'X-Api-Key: abc123' \
    -d '{"parameters": [ 1, "foo", "bar" ]}'
    

    并保存结果,然后看看它与:

    library(httr)
    
    result <- POST("http://httpbin.org/post",
                   verbose(),
                   encode="json",
                   add_headers(`X-Api-Key`="abc123"),
                   body=list(parameters=c(1, "foo", "bar")))
    
    content(result)
    

    这是一个非常简单的映射。

    【讨论】:

    • 如果你使用encode = "json",你可以删除content_type_json()
    【解决方案3】:

    关键是转义标题名称,以防有人好奇。直接翻译如下:

    POST("http://httpbin.org/post",
    add_headers(`X-Api-Key`="abc123", `Content-Type` = "application/json"),
    body='{"parameters": [ 1, "foo", "bar" ]}')
    

    【讨论】:

      猜你喜欢
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 2016-01-08
      • 2018-03-28
      相关资源
      最近更新 更多