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;
I'm using idhttp (Indy) to do some website checking. All I want it to do is check the response code from the server after my request has been sent, I don't want to actually have to receive the HTML output from the server as I'm only monitoring for a 200 OK code, any other code meaning there is an issue of some form.
I've looked up idhttp help documents and the only way I could see to possible do this would be to assign the code to a MemoryStream
and then just clear it straight away, however that isn't very efficient and uses memory that isn't needed. Is there a way to just call a site and get the response but ignore the HTML sent back that is more efficient and doesn't waste memory?
Currently the code would look something like this. However this is just sample code which I haven't tested yet, I'm just using it to explain what I'm trying to do.
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
TIdHTTP.Head()
是最好的选择。但是,作为替代方案,在最新版本中,您可以使用
nil
目标TStream
或调用
未分配任何事件处理程序,并且TIdHTTP.Get()
>TIdEventStreamTIdHTTP
仍将读取服务器的数据,但不会将其存储在任何地方。无论哪种方式,还要记住,如果服务器发回失败响应代码,
TIdHTTP
将引发异常(除非您使用AIgnoreReplies
参数指定特定响应代码值您有兴趣忽略),因此您也应该考虑到这一点,例如:更新:为了避免在失败时引发
EIdHTTPProtocolException
,您可以启用hoNoProtocolErrorException
标志TIdHTTP.HTTPOptions
属性:TIdHTTP.Head()
is the best option.However, as an alternative, in the latest version, you can call
TIdHTTP.Get()
with anil
destinationTStream
, or aTIdEventStream
with no event handlers assigned, andTIdHTTP
will still read the server's data but not store it anywhere.Either way, also keep in mind that if the server sends back a failure response code,
TIdHTTP
will raise an exception (unless you use theAIgnoreReplies
parameter to specify specific response code values you are interested in ignoring), so you should account for that as well, eg:UPDATE: to avoid the
EIdHTTPProtocolException
being raised on failures, you can enable thehoNoProtocolErrorException
flag in theTIdHTTP.HTTPOptions
property:尝试使用
http.head()
而不是http.get()
。Try with
http.head()
instead ofhttp.get()
.