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

curl请求API成功时自动跳转,如何不跳转即可获取返回的JSON数据?

解决方案

你当前的cURL配置默认不会处理3xx重定向响应,因此接口请求成功返回跳转时,你拿到的$result是重定向响应内容而非目标页的JSON数据,可通过以下两种方案实现需求:


方案一:开启cURL自动跟随重定向(最简便,适合绝大多数场景)

只需在现有cURL配置中新增2行配置即可,cURL会自动跟随重定向到目标地址,直接返回跳转后页面的内容:

  • 新增CURLOPT_FOLLOWLOCATION参数设为true,开启自动跟随重定向能力
  • 新增CURLOPT_MAXREDIRS参数限制最大跳转次数,避免陷入无限跳转异常

修改后的完整代码如下:

$url = "urlprovided";

$fields = [
    "Username" => "sample",
    "Password" => "sample",
];

$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); 
curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
// 新增以下两行配置
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
// 如有会话校验要求,可额外加Cookie配置:
// curl_setopt($ch, CURLOPT_COOKIEJAR, '');
// curl_setopt($ch, CURLOPT_COOKIEFILE, '');

// 执行请求
$result = curl_exec($ch);
// 可选:获取最终响应状态码,判断请求结果
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$array = json_decode($result, true);
var_dump($array);

方案二:手动捕获重定向地址请求(适合需要自定义跳转逻辑的场景)

如果你需要对跳转逻辑做自定义处理,可以关闭自动跟随重定向,主动提取响应头中的Location字段,再单独请求该地址获取数据:

$url = "urlprovided";

$fields = [
    "Username" => "sample",
    "Password" => "sample",
];

$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
// 开启获取响应头
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); 
curl_setopt($ch, CURLOPT_TIMEOUT, 10); 

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// 判断是否为重定向响应
if (in_array($httpCode, [301,302,303,307,308])) {
    // 提取响应头中的Location字段
    preg_match('/Location:\s*(.*?)\s*$/i', $response, $matches);
    if (!empty($matches[1])) {
        $redirectUrl = trim($matches[1]);
        // 处理相对路径跳转的情况,补全域名
        if (!str_starts_with($redirectUrl, 'http')) {
            $redirectUrl = "https://samplesite/" . ltrim($redirectUrl, '/');
        }
        // 请求跳转地址获取JSON
        $ch = curl_init($redirectUrl);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        $array = json_decode($result, true);
    }
} else {
    // 非重定向,直接解析错误JSON
    $array = json_decode($response, true);
}

var_dump($array);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:27:04