php请求库guzzlehttp/guzzle:~6.0拦截请求异常,自定义处理异常案例

$httpCookie = new \GuzzleHttp\Cookie\CookieJar;
$httpClient = new \GuzzleHttp\Client([
    // Base URI is used with relative requests
    // 'base_uri' => 'http://httpbin.org',
    // You can set any number of default request options.
    'timeout'  => 60,
    'cookies'  => &$httpCookie, // 使用地址引用,这样后续cookie失效才能更新到
    'verify'   => false,
    'headers'   => [
        'Accept' => 'application/json',
        'Accept-Encoding' => 'gzip, deflate, br',
        'Accept-Language' => 'zh-CN,zh;q=0.9',
        'Content-Type' => 'application/x-www-form-urlencoded',
        'Sec-Ch-Ua' => '"Google Chrome";v="117", "Not;A=Brand";v="8", "Chromium";v="117"',
        'Sec-Ch-Ua-Mobile' => '?0',
        'Sec-Ch-Ua-Platform' => '"Windows"',
        'Sec-Fetch-Dest' => 'empty',
        'Sec-Fetch-Mode' => 'cors',
        'Sec-Fetch-Site' => 'cross-site',
        'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36',
    ]
]);

$url = 'https://baidu.com/_abc_123_404';
try {
    $response = $httpClient->get($url);
}
catch (\GuzzleHttp\Exception\RequestException $e) {
    $request =  \GuzzleHttp\Psr7\str($e->getRequest());
    if ($e->hasResponse()) {
        $response =  \GuzzleHttp\Psr7\str($e->getResponse());
    }
    $httpStatus = $e->getCode(); // 响应状态码
}
// ... 请求正常,解析响应数据
$bodyContents = $response->getBody()->getContents();

参考

  • guzzlehttp 6.0 | 异常

你可能感兴趣的:(php,开发语言)