【问题标题】:How to Retrieve HTTP Status Code with Guzzle?如何使用 Guzzle 检索 HTTP 状态码?
【发布时间】:2018-10-12 14:15:39
【问题描述】:

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());

}

【问题讨论】:

    标签: guzzle http-status-codes guzzle6


    【解决方案1】:

    您可以使用getStatusCode 函数。

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

    注意:如果您的 URL 重定向到其他 URL,那么您需要为 allow_redirects 属性设置 false 值,以便能够检测父 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()

    【讨论】:

      【解决方案2】:

      您也可以使用此代码:

          $client = new \GuzzleHttp\Client(['base_uri' 'http://...', 'http_errors' => false]);
      

      希望能帮到你

      【讨论】:

      • 感谢您的回答,伊曼纽尔!如果您简要说明您的代码的作用以及解决问题的原因,您的回答将对其他人更有帮助(并且更有可能获得支持)。
      • 谢谢@divibisan!复制那个!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 2014-10-13
      • 2010-09-07
      • 2010-12-26
      相关资源
      最近更新 更多