【问题标题】:How translate this curl command into a R curl call?如何将此 curl 命令转换为 R curl 调用?
【发布时间】:2019-06-20 02:27:08
【问题描述】:

我有可以在 bash 中调用的 curl 命令

curl -X POST -H 'Content-Type: text/csv' --data-binary @data/data.csv https://some.url.com/invocations > data/churn_scored.jsonl

将 CSV 文件发布到 API 端点,然后我将结果重定向到 .jsonl 文件。

我找不到像使用 curl 的 @ 一样指定要 POST 到端点的数据文件的位置。

使用 R 的 curl 包(或任何其他包)实现 CURL 帖子的方法是什么?输出的重定向我可以用另一种方式弄清楚。

【问题讨论】:

标签: r curl


【解决方案1】:

这是一个将 curl 命令转换为其他语言的非常有用的网站:https://curl.trillworks.com/#r

当我插入你的 curl 命令时,我得到了这个。

require(httr)

headers = c(
  `Content-Type` = 'text/csv'
)

data = upload_file('data/data.csv')
res <- httr::POST(url = 'https://some.url.com/invocations', httr::add_headers(.headers=headers), body = data)

【讨论】:

    【解决方案2】:

    到特定符号@。来自man curl

    --data-binary <data>
      (HTTP) This posts data exactly as specified with no extra processing whatsoever.
      If you start the data with the letter @, the rest should be a filename.  Data is
      posted in a similar manner as --data-ascii does, except that newlines are preserved
      and conversions are never done.
    
      If this option is used several times, the ones following the first will append data
      as described in -d, --data.
    

    看来不用担心@

    正如@chinsoon12 提到的,httr 是处理请求的好方法:

    • -X--request 转换为VERB 函数POST(),其中包括--data-binary
    • -H--header 转换为 add_headers() 但有设置内容类型的特殊功能(见下文)

    所以它看起来像:

    library(httr)
    response <- POST(
          url = "https://some.url.com/invocations",
          body = upload_file(
            path =  path.expand("data/data.csv"),
            type = 'text/csv'),
          verbose()
        )
    # get response and write to you disk
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-10
      • 2021-10-08
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多