代码之家  ›  专栏  ›  技术社区  ›  xiaodai

如何将这个curl命令转换为r curl调用?

  •  0
  • xiaodai  · 技术社区  · 7 年前

    我有这个curl命令,可以在bash中调用

    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那样指定要发布到端点的数据文件 @ .

    使用r的curl包(或任何其他包)实现curl post的方法是什么?输出的重定向我可以用另一种方法来解决。

    0 回复  |  直到 6 年前
        1
  •  2
  •   casonadams    7 年前

    在将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
  •  1
  •   Dylan    7 年前

    到特定符号 @ . 从 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