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

使用R的httr2/httr包请求GFW API令牌时遇HTTP错误求助

GFW API令牌获取问题解决方法

你的问题核心是请求体格式不匹配:GFW的令牌接口要求使用表单编码(application/x-www-form-urlencoded),但你之前的代码要么发送了JSON格式,要么没正确触发表单编码逻辑。以下是两种R包的正确实现:

1. 使用httr2包的正确代码

httr2提供了req_body_form()方法,专门处理表单编码的请求体,无需手动设置Content-Type(工具会自动添加正确的头部):

library(httr2)

# 替换为你的GFW账号信息
username <- "你的用户名"
password <- "你的密码"

req_token <- request("https://data-api.globalforestwatch.org/auth/token") %>%
  req_body_form(username = username, password = password) 

resp_token <- req_perform(req_token)

# 解析响应提取令牌
token <- resp_body_json(resp_token)$access_token

2. 使用httr包的正确代码

在httr的POST()函数中,需要指定encode = "form"来将列表转换为表单编码格式,而不是手动设置Content-Type:

library(httr)

# 替换为你的GFW账号信息
username <- "你的用户名"
password <- "你的密码"

url <- "https://data-api.globalforestwatch.org/auth/token"
data <- list(username = username, password = password)

resp <- POST(url, body = data, encode = "form")

# 解析响应提取令牌
token <- content(resp, "parsed")$access_token

注意事项

  • 不要手动添加Content-Type: application/x-www-form-urlencoded头部,httr/httr2在使用表单编码时会自动生成正确的头部,手动设置可能导致格式冲突。
  • 确保账号信息正确,GFW的令牌接口需要有效的注册账号(可能需要验证邮箱)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 20:58:29