delphi IdHttp 只获取响应代码  
官方Delphi 学习QQ群: 682628230(三千人)\n
频道

delphi IdHttp 只获取响应代码


TIdHTTP.Head() 是最好的选择。

但是,作为替代方案,在最新版本中,您可以TIdHTTP.Get()使用nildestinationTStream或未TIdEventStream分配事件处理程序的a进行调用,并且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在失败时引发,您可以hoNoProtocolErrorException在TIdHTTP.HTTPOptions属性中启用标志:

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;



推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.045085906982422 seconds