中断HTTP GET操作

时间:2017-08-07 09:41:15

标签: delphi network-programming delphi-7 indy

在特殊诊断模式下,我通过在已知的始终预期要生存的服务器上执行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;

1 个答案:

答案 0 :(得分:2)

您可以通过从与执行方法的线程不同的线程的上下文中调用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;