IdHttp Just Get Response Code

2019-02-06 19:10发布

问题:

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;

回答1:

TIdHTTP.Head() is the best option. However, as an alternative, in the latest version you can call TIdHTTP.Get() with a nil destination TStream, or a TIdEventStream with no event handlers assigned, and it 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 ResponseCode, TIdHTTP will raise an exception (unless you use the AIgnoreReplies parameter to specify specific ResponseCode values you are interested in), so you should account for that as well, eg:

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; 


回答2:

Try with http.head() instead of http.get().