IdHttp刚刚获取响应代码

时间:2011-02-10 20:11:58

标签: delphi indy idhttp

我正在使用idhttp(Indy)进行一些网站检查。我想要它做的就是在我的请求发送后检查来自服务器的响应代码,我不想实际上必须从服务器接收HTML输出,因为我只监视200 OK代码,任何其他代码意味着存在某种形式的问题。

我查了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;

2 个答案:

答案 0 :(得分:14)

TIdHTTP.Head()是最佳选择。但是,作为替代方案,在最新版本中,您可以使用nil目标TIdHTTP.Get()调用TStream,或者在没有分配事件处理程序的情况下调用TIdEventStream,它仍然会读取服务器的数据但是不要把它存放在任何地方。

无论哪种方式,还要记住,如果服务器发回一个失败的ResponseCode,TIdHTTP将引发异常(除非你使用AIgnoreReplies参数指定你感兴趣的特定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; 

答案 1 :(得分:8)

尝试使用http.head()代替http.get()