Fla*_*lyn 10 delphi indy idhttp
我正在使用idhttp(Indy)做一些网站检查.我想要它做的就是在我的请求发送后检查来自服务器的响应代码,我不想实际上必须从服务器接收HTML输出,因为我只监视200 OK代码,任何其他代码意味着存在某种形式的问题.
我查了idhttp帮助文档,我能看到的唯一方法就是将代码分配给a MemoryStream,然后立即清除它,但这不是很有效并且使用不需要的内存.有没有办法只是调用一个站点并获得响应,但忽略发回的HTML更高效,不浪费内存?
目前代码看起来像这样.然而,这只是我尚未测试的示例代码,我只是用它来解释我正在尝试做什么.
Procedure Button1Click(Sender: TObject);
var
http : TIdHttp;
s : TStream;
url : string;
code : integer;
begin
s := TStream.Create();
http := Tidhttp.create();
url := 'http://www.WEBSITE.com';
try
http.get(url,s);
code := http.ResponseCode;
ShowMessage(IntToStr(code));
finally
s.Free();
http.Free();
end;
Run Code Online (Sandbox Code Playgroud)
Rem*_*eau 14
TIdHTTP.Head()是最好的选择.但是,作为替代方案,在最新版本中,您可以TIdHTTP.Get()使用nil目标调用nil,或者TStream不分配事件处理程序,它仍将读取服务器的数据,但不会将其存储在任何位置.
无论哪种方式,还要记住,如果服务器发回一个失败的ResponseCode,TIdHTTP将引发一个异常(除非你使用该TIdEventStream参数来指定你感兴趣的特定ResponseCode值),所以你也应该考虑到这一点,例如:
procedure Button1Click(Sender: TObject);
var
http : TIdHttp;
url : string;
code : integer;
begin
url := 'http://www.WEBSITE.com';
http := TIdHTTP.Create(nil);
try
try
http.Head(url);
code := http.ResponseCode;
except
on E: EIdHTTPProtocolException do
code := http.ResponseCode; // or: code := E.ErrorCode;
end;
ShowMessage(IntToStr(code));
finally
http.Free;
end;
end;
procedure Button2Click(Sender: TObject);
var
http : TIdHttp;
url : string;
code : integer;
begin
url := 'http://www.WEBSITE.com';
http := TIdHTTP.Create(nil);
try
try
http.Get(url, nil);
code := http.ResponseCode;
except
on E: EIdHTTPProtocolException do
code := http.ResponseCode; // or: code := E.ErrorCode;
end;
ShowMessage(IntToStr(code));
finally
http.Free;
end;
end;
Run Code Online (Sandbox Code Playgroud)