如何解决Laravel guzzlehttp-如何检查主机是否在线?
当我尝试连接到脱机或不存在的主机时,出现异常:
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 Client抛出一组异常。 可以从异常中得到响应。
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.
}
}
,
如果您想使用超时,那么我可以通过使用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中了解有关它们的更多信息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。