当我尝试连接到离线或不存在的主机时,出现异常:
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/