You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用R语言的httr::POST函数下载POST请求返回的文件?

使用httr::POST实现POST请求下载文件

你完全可以用httr::POST实现和curl命令等效的文件下载功能,核心是用write_disk()参数替代curl的--output选项,以下是具体实现:

等效代码示例(对应你的curl命令)

library(httr)

# 配置请求基础信息
target_url <- "http://localhost/requestDownloadFile"
request_headers <- add_headers(
  accept = "*/*",
  `Content-Type` = "application/json"
)
# 替换为你实际的JSON请求体
json_payload <- '{APPLICATION_JSON_REQUEST_PAYLOAD}'

# 发送POST请求并保存文件
download_response <- POST(
  url = target_url,
  config = request_headers,
  body = json_payload,
  encode = "raw",  # 确保JSON字符串原样发送,不额外编码
  write_disk("foo.pdf", overwrite = TRUE)  # 对应curl的--output,overwrite可选
)

# 可选:验证请求是否成功(非200状态码会抛出错误)
stop_for_status(download_response)

参数对应说明

  • POST(url):对应curl的-X POST和目标URL
  • add_headers():对应curl的-H请求头参数
  • body = json_payload + encode = "raw":对应curl的-d参数,因为你提供的是现成的JSON字符串,用raw编码避免httr自动修改内容
  • write_disk("foo.pdf", overwrite = TRUE):完全等效于curl的--output foo.pdf,overwrite = TRUE允许覆盖已存在的文件,和curl默认行为一致

更贴合R风格的写法(推荐)

如果你的请求体可以用R列表构造,不需要手动写JSON字符串,可以用encode = "json"让httr自动处理编码:

library(httr)

target_url <- "http://localhost/requestDownloadFile"
request_headers <- add_headers(accept = "*/*")

# 用R列表定义请求体,httr会自动转为JSON
payload_list <- list(
  param1 = "your_value1",
  param2 = 456,
  param3 = list(sub_param = "sub_value")
)

download_response <- POST(
  url = target_url,
  config = request_headers,
  body = payload_list,
  encode = "json",  # 自动将R列表转为JSON格式
  write_disk("foo.pdf", overwrite = TRUE)
)

stop_for_status(download_response)

内容的提问来源于stack exchange,提问作者Dutts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 19:12:31