向R curl_fetch_memory()添加--数据

whhtz7ly  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(105)

我想创建一个R脚本来代替curl请求。
使用curl,我使用了一个需要--data选项的谷歌API。我不确定如何使用curl包将此选项添加到我的curl请求中。
使用Git Bash的请求如下所示:

API_KEY="[xyz]"
curl "https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord?key=$API_KEY" \
--header 'Content-Type: application/json' \
–-data '{"url": "https://www.example.com/"}'

这是我的R代码,它不发送必要的URL来返回任何有用的信息:
x一个一个一个一个x一个一个二个x
那么,如何使用curl包添加--data选项呢?

ujv3wf0j

ujv3wf0j1#

如果确实需要,可以使用较低级别的curl,在本例中,原始的CURL命令使用JSON编码的主体执行POST操作。

library(curl)

API_KEY <- "xyz"
url <- paste0("https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord?key=", API_KEY)
payload <- charToRaw('{"url": "https://www.example.com/"}')

h <- new_handle()
handle_setopt(h, post=TRUE, postfields=payload)
handle_setheaders(h, "Content-Type" = "application/json")
r <- curl_fetch_memory(url = url, h)

cat(rawToChar(r$content))

相关问题