Guzzle:处理400个不良请求

时间:2014-07-30 15:10:08

标签: php laravel bad-request guzzle

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

 [status code] 400 [reason phrase] Bad Request

使用:

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

如何解决? 感谢,

2 个答案:

答案 0 :(得分:46)

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

  

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

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

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->getResponse()->getStatusCode() == '400') {
            echo "Got response 400";
    }

    // You can check for whatever error status code you need 

} catch (\Exception $e) {

    // There was another exception.

}

答案 1 :(得分:10)

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

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