当curl
命令中有-d
/--data
时,它实际上是一个带有表单数据的POST
调用(即它不能与httr::GET()
一起工作)
httr
的继承者httr2
附带了curl_translate()
工具,它试图为你翻译curl
个命令,结果通常是有点原始,但应该会给你正确的方向:
httr2::curl_translate('curl https://api.todoist.com/sync/v9/completed/get_all \ -H "Authorization: Bearer 000api_key000" \ -d limit=200')
#> request("https://api.todoist.com/sync/v9/completed/get_all") %>%
#> req_headers(
#> Authorization = "Bearer 000api_key000",
#> ) %>%
#> req_body_raw("limit=200", "application/x-www-form-urlencoded") %>%
#> req_perform()
要判断将发送到服务器的内容,我们可以将req_perform()
临时替换为req_dry_run()
:
library(httr2)
request("https://api.todoist.com/sync/v9/completed/get_all") |>
req_headers(
Authorization = "Bearer 000api_key000",
) |>
req_body_raw("limit=200", "application/x-www-form-urlencoded") |>
req_dry_run()
#> POST /sync/v9/completed/get_all HTTP/1.1
#> Host: api.todoist.com
#> User-Agent: httr2/0.2.3 r-curl/5.1.0 libcurl/8.3.0
#> Accept: */*
#> Accept-Encoding: deflate, gzip
#> Authorization: <REDACTED>
#> Content-Type: application/x-www-form-urlencoded
#> Content-Length: 9
#>
#> limit=200
由于有适当的方法用于承载令牌和表单正文,因此可以将相同的请求写为:
request("https://api.todoist.com/sync/v9/completed/get_all") |>
req_auth_bearer_token("000api_key000") |>
req_body_form(limit = 200) |>
req_dry_run()
#> POST /sync/v9/completed/get_all HTTP/1.1
#> Host: api.todoist.com
#> User-Agent: httr2/0.2.3 r-curl/5.1.0 libcurl/8.3.0
#> Accept: */*
#> Accept-Encoding: deflate, gzip
#> Authorization: <REDACTED>
#> Content-Type: application/x-www-form-urlencoded
#> Content-Length: 9
#>
#> limit=200
如果你需要帮助翻译成httr
,也有https://curlconverter.com/r/,这将返回:
require(httr)
headers = c(
`Authorization` = "Bearer 000api_key000",
`Content-Type` = "application/x-www-form-urlencoded"
)
data = list(
`limit` = "200"
)
res <- httr::POST(url = "https://api.todoist.com/sync/v9/completed/get_all", httr::add_headers(.headers=headers), body = data, encode = "form")