gpt4 book ai didi

delphi - 中断 HTTP GET 操作

转载 作者:行者123 更新时间:2023-12-01 19:03:20 26 4
gpt4 key购买 nike

在特殊的诊断模式下,我通过在已知的始终预期事件的服务器上执行 HTTP GET 操作来测试互联网连接。虽然这通常非常快,但在远程位置工作或禁用计算机网络适配器时,这可能会很慢并且/或在 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;

关于delphi - 中断 HTTP GET 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45543837/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com