Guzzle:处理400个不良请求

mwa*_*afi 19 php bad-request laravel guzzle

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

 [status code] 400 [reason phrase] Bad Request
Run Code Online (Sandbox Code Playgroud)

使用:

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

怎么解决?谢谢,

Hpa*_*oio 50

正如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.

}
Run Code Online (Sandbox Code Playgroud)


小智 12

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

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