在特殊的诊断模式下,我通过在已知的始终预期要运行的服务器上执行HTTP GET操作来测试Internet连接。尽管这通常非常快,但是在远程位置或禁用计算机网络适配器时,这可能很慢和/或在15秒或更长时间后超时。
是否可以配置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;
最佳答案
您可以通过从与执行该方法的线程不同的线程上下文中调用TIdHTTP来中断正在运行的Disconnect HTTP方法。对于您的设计,这意味着以某种方式公开内部使用的TIdHTTP对象。
但是对于您的任务,您可以给InternetCheckConnection函数尝试一下。例如对于Delphi 7,它可能是:
const
FLAG_ICC_FORCE_CONNECTION = $00000001;
function InternetCheckConnectionA(lpszUrl: PAnsiChar; dwFlags: DWORD; dwReserved: DWORD): BOOL; stdcall;
external 'wininet.dll' name 'InternetCheckConnectionA';
function InternetCanConnect(const URL: AnsiString): Boolean;
begin
Result := Boolean(InternetCheckConnectionA(PAnsiChar(URL), FLAG_ICC_FORCE_CONNECTION, 0));
end;
function InternetNotConnected(const URL: AnsiString): Boolean;
begin
Result := not Boolean(InternetCheckConnectionA(PAnsiChar(URL),
FLAG_ICC_FORCE_CONNECTION, 0)) and (GetLastError = ERROR_NOT_CONNECTED);
end;