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

cURL转R的httr::GET请求遇400错误,求排查及-G参数处理

问题分析与修正方案

首先,你的转换思路是对的——cURL的-G参数确实是把-d指定的表单参数转换成GET请求的查询字符串,对应到httr::GET()里用query参数传递是正确的方向。但你的R代码里有几个明显的问题导致400错误:

1. 拼写错误

你把cabin_class的值写成了"ecomony",正确的应该是"economy"——这个拼写错误会让API无法识别舱位类型,直接触发无效请求。

2. 多值参数currencies[]的处理方式不对

在httr中,传递多值的查询参数不需要重复写键名(比如"currencies[]"="SEK", "currencies[]"="USD"),而是应该把参数值设为一个向量。当你用向量时,httr会自动生成符合API要求的重复键名格式(也就是currencies[]=SEK&currencies[]=USD)。

3. 修正后的完整代码

这里是调整后的正确R代码:

library(httr)

api.key <- "YOUR_API_KEY"

r <- GET(
  url = "https://api.goclimate.com/v1/flight_footprint",
  authenticate(api.key, ""),
  query = list(
    "segments[0][origin]" = "ARN",
    "segments[0][destination]" = "BCN",
    "segments[1][origin]" = "BCN",
    "segments[1][destination]" = "ARN",
    "cabin_class" = "economy",
    currencies = c("SEK", "USD")
  )
)

# 可以查看响应内容确认结果
content(r)

额外验证小技巧

如果想确认生成的请求URL是否和cURL的一致,可以用httr::build_url()查看最终的查询字符串:

req <- GET(
  url = "https://api.goclimate.com/v1/flight_footprint",
  authenticate(api.key, ""),
  query = list(
    "segments[0][origin]" = "ARN",
    "segments[0][destination]" = "BCN",
    "segments[1][origin]" = "BCN",
    "segments[1][destination]" = "ARN",
    "cabin_class" = "economy",
    currencies = c("SEK", "USD")
  )
)

build_url(req$url)

这个结果应该和cURL加上-G后生成的URL完全一致,这样就能确保参数传递是正确的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:42:46