php - Laravel guzzlehttp - 如何检查主机是否在线?

标签 php laravel guzzle

当我尝试连接到离线或不存在的主机时,出现异常:

cURL error 6: Could not resolve host: somedomain.com

那你怎么用这些东西呢? ( https://laravel.com/docs/8.x/http-client )

$response->body() : string;
$response->json() : array|mixed;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->failed() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;

我需要知道主机是否在线/离线。

编辑:

use Illuminate\Support\Facades\Http;
use GuzzleHttp\Exception\RequestException;


public function checkSiteStatus($host)
{
    try {
        return Http::timeout(2)->get($host);
    } catch (RequestException $e) {
        //Access the message or other type of errors and react to them

        if (!$e->hasResponse()) {
            //No response from server. Assume the host is offline or server is overloaded.
            return 'offline';
        }
        
        return 'offline';
    }
}

它对我不起作用,我总是得到:cURL 错误 6:无法解析主机:somedomain.com

最佳答案

Guzzle HTTP 客户端抛出一组异常。 有可能从异常中得到响应。

http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions

use GuzzleHttp\Exception\RequestException;

try {
    $client->request('GET', 'https://github.com/_abc_123_404');
} catch (RequestException $e) {
    //Access the message or other type of errors and react to them
    $e->getMessage();
    if (! $e->hasResponse()) {
        //No response from server. Assume the host is offline or server is overloaded.
    }
}

关于php - Laravel guzzlehttp - 如何检查主机是否在线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64258785/

相关文章:

php - 如何在 Laravel 中覆盖 auth 登录功能

Laravel 多个 whereIn 数组

php - 我怎样才能在 Laravel 5.3 中得到 guzzle 6 的响应?

php - 如何使用 Guzzle 模拟特定 URL 的响应?

php - 从表中选择组合字段

php - $_Session "complication"登录和注销 php

laravel - 无法获取工匠队列:work to process jobs with Supervisor on Elastic Beanstalk (Laravel/Redis)

php - 在 guzzle 6 中初始化后设置请求选项

php - 为什么这个 PHP/SQL 不创建表?

.htaccess - Laravel 默认 .htaccess 文件将不起作用