【问题标题】:Laravel guzzlehttp - How to check if the host is online?Laravel guzzlehttp - 如何检查主机是否在线?
【发布时间】:2020-10-08 08:36:02
【问题描述】:

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

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

【问题讨论】:

  • 你有离线主机测试吗?
  • 嗯。事实上,我没有。我会得到一个域名或ip地址,需要检查服务器是否在线。有时我得到一个不存在的域。
  • 这能回答你的问题吗? Laravel ping IP to check online or offline status

标签: php laravel guzzle


【解决方案1】:

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.
    }
}

【讨论】:

  • @kamilon123s 你得到什么结果?
【解决方案2】:

如果你想使用超时,那么我可以通过使用 guzzlehttp 来提供一个选项。

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;


public function checkSiteStatus($host)
{
    define("read_timeout", \GuzzleHttp\RequestOptions::READ_TIMEOUT );
    try {
        $client = new Client();
        $response = $response = $client->get(
                $host, [
                'headers' => [
                    // your headers if any
                ],
                'stream' => true,
                'read_timeout' => 2,
            ]);
        $body = $response->getBody();

       // Returns false on timeout
       $data = $body->read(1024);
       // Returns false on timeout
       $line = fgets($body->detach());
       // you can use $data or $line if they are false means there is timeout.
    } catch (RequestException $e) {
        //Access the message or other type of errors and react to them
    }
}

您可以在docs 中阅读有关它们的更多信息。

【讨论】:

  • stream as true 是必需的,它将流式传输响应而不是预先下载所有响应。
猜你喜欢
  • 2018-03-21
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 2012-07-09
  • 2023-03-13
  • 1970-01-01
  • 2012-08-21
  • 2021-06-26
相关资源
最近更新 更多