Guzzle替换Curl后小米运动登录请求返回结果差异的原因是什么?

guzzle替换curl后小米运动登录请求返回结果差异的原因是什么?

Guzzle替换Curl后小米运动登录请求返回结果差异分析及解决方案

本文分析了使用PHP进行小米运动账号登录时,将基于cURL的请求方式替换为Guzzle后,返回结果出现差异的原因,并提供了解决方案。问题源于一个用于小米运动账号登录的代码片段,其request_post函数最初使用cURL进行HTTP请求。为了提升代码可维护性和效率,开发者尝试将其替换为Guzzle,然而,替换后请求的HTTP状态码从303变为200,返回数据也不一致。

原cURL实现的request_post函数:

function request_post($url = '', $post_data = array(), $header = array()) {
    if (empty($url) || empty($post_data)) {
        return false;
    }
    if (empty($header)) {
        $header = []; // 修正:空数组,而非0
    }
    $o = "";
    foreach ($post_data as $k => $v) {
        $o .= "$k=" . urlencode($v) . "&";
    }
    $post_data = substr($o, 0, -1);
    $posturl = $url;
    $curlpost = $post_data;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $posturl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, true);// 返回 response_header
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlpost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}
登录后复制

使用Guzzle重写的代码:

use IlluminateSupportFacadesHttp;

// ...  $url, $data, $header 的定义 ...

$response = Http::asForm()->withHeaders($header)->post($url, $data);
登录后复制

问题根源:

cURL实现默认会跟随HTTP重定向(303状态码表示重定向),而Guzzle的Http facade默认也会跟随重定向。小米运动的登录流程可能包含重定向步骤,cURL跟随重定向后返回最终结果,而Guzzle在重定向之前返回了200状态码和不同的数据。

解决方案:使用Guzzle的withoutRedirecting()方法

为了解决这个问题,需要使用Guzzle的withoutRedirecting()方法禁止自动跟随重定向:

$response = Http::asForm()->withHeaders($header)->withoutRedirecting()->post($url, $data);
登录后复制

添加withoutRedirecting()后,Guzzle将不再自动跟随重定向,从而得到与cURL实现一致的HTTP状态码和数据。 后续代码需要根据重定向返回的Location header手动处理重定向,获取最终的登录结果。

完整的示例:

$response = Http::asForm()->withHeaders($header)->withoutRedirecting()->post($url, $data);
$location = $response->header('Location');
if ($location) {
    $query = parse_url($location, PHP_URL_QUERY);
    parse_str($query, $queryParams);
    // ... 使用 $queryParams 处理重定向后的数据 ...
    //  例如再次发送请求获取最终结果
    $finalResponse = Http::asForm()->withHeaders($header)->post($location, $queryParams);
    // ... 处理 $finalResponse ...
} else {
    // 处理没有重定向的情况
}
登录后复制

通过以上方法,可以确保Guzzle在处理小米运动登录请求时,行为与cURL一致,从而避免返回结果差异。 记住处理潜在的Location header以完成完整的登录流程。 代码中也修正了原cURL代码中$header变量初始化为0的错误,应初始化为空数组。

以上就是Guzzle替换Curl后小米运动登录请求返回结果差异的原因是什么?的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1239252.html

发表回复

Your email address will not be published. Required fields are marked *