我正在使用idhttp (Indy)做一些网站检查。我所要做的就是在我的请求被发送后检查来自服务器的响应码,我不想实际上必须从服务器接收HTML输出,因为我只监控200OK代码,任何其他代码都意味着存在某种形式的问题。
我查阅了idhttp帮助文档,唯一可能做到这一点的方法是将代码分配给一个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;发布于 2011-02-11 05:33:09
TIdHTTP.Head()是最佳选择。
但是,作为替代方案,在最新版本中,您可以使用nil目标TStream调用TIdHTTP.Get(),或者在未分配事件处理程序的情况下调用TIdEventStream,TIdHTTP仍将读取服务器的数据,但不会将其存储在任何位置。
无论哪种方式,也请记住,如果服务器发回失败响应代码,TIdHTTP将引发异常(除非您使用AIgnoreReplies参数指定您有兴趣忽略的特定响应代码值),因此您也应该考虑到这一点,例如:
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;更新:为了避免在失败时引发EIdHTTPProtocolException,您可以在TIdHTTP.HTTPOptions属性中启用hoNoProtocolErrorException标志:
procedure Button1Click(Sender: TObject);
var
http : TIdHttp;
url : string;
code : integer;
begin
url := 'http://www.WEBSITE.com';
http := TIdHTTP.Create(nil);
try
http.HTTPOptions := http.HTTPOptions + [hoNoProtocolErrorException];
http.Head(url);
code := http.ResponseCode;
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
http.HTTPOptions := http.HTTPOptions + [hoNoProtocolErrorException];
http.Get(url, nil);
code := http.ResponseCode;
ShowMessage(IntToStr(code));
finally
http.Free;
end;
end;发布于 2011-02-11 04:22:20
尝试使用http.head()而不是http.get()。
https://stackoverflow.com/questions/4962096
复制相似问题