sin*_*rba 4 http-status-codes guzzle guzzle6
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());
}
Run Code Online (Sandbox Code Playgroud)
您可以使用该getStatusCode功能。
$response = $client->request('GET', $url);
$statusCode = $response->getStatusCode();
Run Code Online (Sandbox Code Playgroud)
注意:如果您的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]);
Run Code Online (Sandbox Code Playgroud)
如果要检查catch块中的状态码,则需要使用$exception->getCode()
| 归档时间: |
|
| 查看次数: |
5152 次 |
| 最近记录: |