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

使用Http客户端调用气候API时$response->getBody()返回NULL的问题

问题解决:Laravel Http请求Open-Meteo API返回NULL

可能原因及解决方案

1. 请求参数格式错误

你当前的Http请求写法中,错误地将查询参数嵌套在了query键下,Laravel的Http::get方法第二个参数直接接收查询参数数组,不需要额外嵌套:

错误写法:

$response = Http::get('https://climate-api.open-meteo.com/v1/climate', [
    'query' => [
        'latitude' => $latitude,
        'longitude' => $longitude,
        'start_date' => $from->format('Y-m-d'),
        'end_date' => $to->format('Y-m-d'),
    ]
]);

正确写法:

$response = Http::get('https://climate-api.open-meteo.com/v1/climate', [
    'latitude' => $latitude,
    'longitude' => $longitude,
    'start_date' => $from->format('Y-m-d'),
    'end_date' => $to->format('Y-m-d'),
]);

这种错误会导致实际请求的URL参数格式变为?query[latitude]=xxx,而非API要求的?latitude=xxx,API可能返回非预期内容(甚至空响应),导致json_decode返回NULL。

2. 排查响应体实际内容

直接输出响应体的原始内容,确认是否为有效JSON:

// 输出原始响应体
\Log::info('Raw response body: ' . (string)$response->getBody());

// 检查JSON解码错误
$body = (string)$response->getBody();
$data = json_decode($body, true);
if ($data === null) {
    \Log::info('JSON decode error: ' . json_last_error_msg());
}

通过日志可以明确:

  • 响应体是否为空
  • 是否是API返回的错误提示JSON(比如参数无效)
  • JSON解码失败的具体原因(如语法错误、编码问题)

3. 验证请求参数有效性

确认$latitude、$longitude、$from、$to变量是否有有效值:

\Log::info('Request params: ', [
    'latitude' => $latitude,
    'longitude' => $longitude,
    'start_date' => $from->format('Y-m-d'),
    'end_date' => $to->format('Y-m-d'),
]);

对比浏览器中能成功请求的参数,确保变量值格式、范围符合API要求(比如经纬度是否在有效区间,日期是否在API支持的范围内)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:25:19