繁体   English   中英

IdHttp刚获取响应代码

[英]IdHttp Just Get Response Code

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

我查看了idhttp帮助文档,并且我看到的唯一可行的方法是将代码分配给MemoryStream ,然后立即将其清除,但是效率不是很高,并且使用的内存不是需要。 有没有一种方法可以只调用一个站点并获得响应,而忽略发送回的HTML,这种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;

TIdHTTP.Head()是最佳选择。

然而,作为替代,在最新的版本中,你可以调用TIdHTTP.Get()nil目的地TStream ,或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;

尝试使用http.head()而不是http.get()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM