Guzzle:处理400个坏请求


Guzzle: handle 400 bad request

我在Laravel 4中使用Guzzle从另一台服务器返回一些数据,但我无法处理错误400错误请求

 [status code] 400 [reason phrase] Bad Request

使用:

$client->get('http://www.example.com/path/'.$path,
            [
                'allow_redirects' => true,
                'timeout' => 2000
            ]);

如何解决?谢谢,

正如Guzzle官方文档中所写:http://guzzle.readthedocs.org/en/latest/quickstart.html

如果异常请求选项设置为true ,则会为400级错误抛出GuzzleHttp''Exception''ClientException

为了正确处理错误,我会使用以下代码:

use GuzzleHttp'Client;
use GuzzleHttp'Exception'RequestException;
try {
    $response = $client->get(YOUR_URL, [
        'connect_timeout' => 10
    ]);
        
    // Here the code for successful request
} catch (RequestException $e) {
    // Catch all 4XX errors 
    
    // To catch exactly error 400 use 
    if ($e->hasResponse()){
        if ($e->getResponse()->getStatusCode() == '400') {
                echo "Got response 400";
        }
    }
    // You can check for whatever error status code you need 
    
} catch ('Exception $e) {
    // There was another exception.
}
$client->get('http://www.example.com/path/'.$path,
            [
                'allow_redirects' => true,
                'timeout' => 2000,
                'http_errors' => true
            ]);

对请求使用http_errors=>false选项。