【问题标题】:How to pass the curl -F parameter in the httr package?如何在 httr 包中传递 curl -F 参数?
【发布时间】:2018-11-24 18:47:23
【问题描述】:

您好,我尝试使用 httr 翻译此 curl 指令

curl -H "Authorization: Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd" -F file=@test.txt -F filename=test.txt -F parent_dir=/ http://cloud.seafile.com:8082/upload-api/73c5d117-3bcf-48a0-aa2a-3f48d5274ae3

没有-F 参数的指令是:

httr::POST(
  url = "http://cloud.seafile.com:8082/upload-api/73c5d117-3bcf-48a0-aa2a-3f48d5274ae3",
  add_headers(Authorization = "Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd")
  )
)

我想我必须使用 httr::upload_file 函数,但我没有成功地使用它。

你知道我该怎么做吗?

问候

【问题讨论】:

  • 我认为这不是你的问题。即使他们未经身份验证的ping 端点也无法正确回复l
  • 在现实生活中我使用我个人的seafile安装,ping和所有其他POST/GET指令都可以

标签: r curl rcurl httr


【解决方案1】:

这里是如何用 httr 包构造这个 curl 请求。我使用 httpbin.org 测试发送的请求。

您将使用POST 用列表填充正文。 encode 参数控制如何处理此列表,默认情况下它是您需要的正确 multipart

res <- httr::POST(
  url = "http://httpbin.org/post",
  httr::add_headers(Authorization = "Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd"),
  # Add the file and metadata as body using a list. Default encode is ok
  body = list(
    file = httr::upload_file("test.txt"),
    filename = "test.txt",
    parent_dir = "/"
  )
)

httr_ouput <- httr::content(res)

检查是否正常的一种方法是将输出与您知道正在运行的 curl 命令进行比较

out <- sys::exec_internal(
       'curl -H "Authorization: Token f2210dacd9c6ccb8133606d94ff8e61d99b477fd" -F file=@test.txt -F filename=test.txt -F parent_dir=/ http://httpbin.org/post'
    )
curl_output <- jsonlite::fromJSON(rawToChar(out$stdout))

#compare body

identical(curl_output$files, httr_ouput$files)
#> TRUE
identical(curl_output$form, httr_ouput$form)
#> TRUE

您也可以使用 crul 包来实现,这是 curl 之上的另一个包装器;逻辑是一样的

con <- crul::HttpClient$new(
  url = "http://httpbin.org/post"
)

crul_req <- con$post(
  body = list(
    file = crul::upload("test.txt"),
    filename = "test.ext",
    parent_dir = "/"
  )
)

crul_output <- jsonlite::fromJSON(crul_req$parse())

【讨论】:

    猜你喜欢
    • 2022-07-07
    • 1970-01-01
    • 2016-01-14
    • 2018-03-25
    • 1970-01-01
    • 2016-11-14
    • 2020-12-22
    • 2018-04-03
    • 1970-01-01
    相关资源
    最近更新 更多