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

如何在R的curl_fetch_memory()中添加--data参数调用Google API

解决方法

要在curl_fetch_memory()中实现curl命令里--data参数的功能,你需要通过handle_setopt()给curl句柄设置postfields参数,同时确保请求头和请求方法正确。以下是修正后的完整代码:

library(curl)

API_KEY = "xyz"
h <- new_handle()

# 设置请求头,指定数据格式为JSON
handle_setheaders(h,
  "Content-Type" = "application/json"
)

# 定义请求体内容,对应curl的--data参数
request_body <- '{"url": "https://www.example.com/"}'
# 给句柄设置POST数据和请求方法
handle_setopt(h,
  postfields = request_body,
  customrequest = "POST" # 明确指定POST请求,可选但更清晰
)

# 发送请求
r <- curl_fetch_memory(
  url = paste0("https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord?key=", API_KEY),
  handle = h
)

# 可选:解析返回的二进制内容为结构化JSON
library(jsonlite)
result <- fromJSON(rawToChar(r$content))
print(result)

关键说明

  • postfields参数直接对应curl命令中的--data,需要传入符合API要求的JSON格式字符串作为请求体
  • 必须保留Content-Type: application/json请求头,否则API无法正确解析你发送的JSON数据
  • 虽然当postfields存在时,curl会自动使用POST请求方法,但显式设置customrequest = "POST"能让代码逻辑更清晰,避免潜在问题
  • 最后可以用jsonlite包将返回的二进制内容转换为R可处理的结构化数据,方便查看和后续操作

内容的提问来源于stack exchange,提问作者Ziemowit Bućko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:15:31