1
在特殊的诊断模式下,我通过在已知的总是预期的活着的服务器上执行HTTP GET操作来测试互联网连接。虽然这通常非常快,但在远程位置工作或禁用计算机网络适配器时,这可能会在15秒或更长时间后变慢和/或超时。中断HTTP GET操作
是否可以配置Indy组件,以便我可以根据需要中断它?或者也许有更好的方法来执行测试HTTP GET操作?我的代码如下,我可能会调用与HasInternet(http://master11.teamviewer.com/);
function HasInternet(strTestWebServer: String) : Boolean;
var
idHTTP: TIdHTTP;
begin
// Test an internet connection to the named server
Result := False;
idHTTP := TIdHTTP.Create(nil);
if (idHTTP <> nil) then
begin
try
try
// Handle redirects in response from HTTP server. Not required for some servers,
// but can confirm a connection to servers that redirect to https.
idHTTP.HandleRedirects := True;
// Add in the HTTP protocol header (if required) and retrieve the HTTP resource
// Note: HTTP_PROTOCOL = 'http://';
if (AnsiPos(HTTP_PROTOCOL, strTestWebServer) > 0) then
Result := (idHTTP.Get(strTestWebServer) <> '')
else
Result := (idHTTP.Get(HTTP_PROTOCOL + strTestWebServer) <> '');
except
// HTTP protocol errors are sometimes returned by servers, with the status code
// saved in TIdHTTP.ResponseCode. Common responses include:
// * 403 Forbidden (request was valid, but server is refusing to respond to it)
// * 404 Not Found (requested resource could not be found)
// * 405 Method Not Allowed (requested method not supported by that resource)
// These errors are counted as "valid connection to the internet possible"
on E: EIdHTTPProtocolException do
// Status code can be found in "E.ReplyErrorCode" or "idHTTP.ResponseCode"
Result := True;
else
// All other exceptions are counted as definite failures
Result := False;
end;
finally
idHTTP.Free();
end;
end;
end;
谢谢!从来不知道“InternetCheckConnectionA”Windows功能。刚刚测试过它。在控制面板中禁用了网络适配器的情况下,两种方法在15秒或更长时间后仍然超时。但是在适配器正常工作的情况下,这种方法要快得多。 – AlainD
请注意,跨线程断开套接字并不总是适用于所有平台。已知“InternetCheckConnection()”会报告不准确的结果。至少,你可以设置TIdHTTP的'ConnectTimeout'和'ReadTimeout'属性,和/或在其OnWork ...事件中引发异常。 –
此外,当您只对检查Internet连接感兴趣时,执行完整的HTTP请求/响应对有点矫枉过正。你可以直接使用'TIdTCPClient'并连接到一个众所周知的服务器端口,而不用实际传输任何数据。 –