gpt4 book ai didi

guzzle - 如何使用Guzzle检索HTTP状态代码?

转载 作者:行者123 更新时间:2023-12-04 13:56:42 26 4
gpt4 key购买 nike

Guzzle/Http的新手。

我有一个API rest url登录名,如果未授权,则用401代码回答;如果缺少值,则用400回答。

我将获取http状态代码以检查是否存在某些问题,但不能仅包含代码(整数或字符串)。

这是我的代码,我在这里使用了指令(http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions)

namespace controllers;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;

$client = new \GuzzleHttp\Client();
$url = $this->getBaseDomain().'/api/v1/login';

try {

$res = $client->request('POST', $url, [
'form_params' => [
'username' => 'abc',
'password' => '123'
]
]);

} catch (ClientException $e) {

//echo Psr7\str($e->getRequest());
echo Psr7\str($e->getResponse());

}

最佳答案

您可以使用getStatusCode函数。

$response = $client->request('GET', $url);
$statusCode = $response->getStatusCode();

注意:如果您的URL重定向到其他URL,则需要为 false属性设置 allow_redirects值,以便能够检测父URL的初始状态代码。

// On client creation
$client = new GuzzleHttp\Client([
'allow_redirects' => false
]);

// Using with request function
$client->request('GET', '/url/with/redirect', ['allow_redirects' => false]);

如果要检查 catch块中的状态码,则需要使用 $exception->getCode()
  • More about responses
  • More about allow_redirects
  • 关于guzzle - 如何使用Guzzle检索HTTP状态代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50135163/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com