Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Response from TIdHttp with Error Code 400

Tags:

delphi

indy

I have been writing a Delphi library for StackApps API.

I have run into a problem with Indy. I am using the version that ships with Delphi 2010. If you pass invalid parameters to one of the StackApps API it will return a HTTP Error Code 400 and then in the response it will contain a JSON object with more details.

By visiting http://api.stackoverflow.com/0.8/stats/?Key=BadOnPurpose in Chrome Browser you can see an Example. I.E. and Firefox hide the JSON.

Using WireShark I can see that the JSON object is returned using the code below, but I am unable to access it using Indy.

For this test code I dropped a TIdHttp component on the form and placed the following code in a button click.

procedure TForm10.Button2Click(Sender: TObject);
var
 SS : TStringStream;
begin
  SS := TStringStream.Create;
  IdHTTP1.Get('http://api.stackoverflow.com/0.8/stats/?Key=BadOnPurpose',SS,[400]);
  Memo1.Lines.Text := SS.DataString;
  SS.Free;
end;

I passed [400] so that it would not raise the 400 exception. It is as if Indy stopped reading the response. As the contents of Memo1 are empty.

I am looking for a way to get the JSON Details.

like image 533
Robert Love Avatar asked Jun 10 '10 20:06

Robert Love


1 Answers

Remove the AIgnoreReplies parameter value from your call to Get(). Let it raise the exception normally. The JSON text you are looking for is in the EIdHTTPProtocolException.ErrorMessage property. For example:

procedure TForm10.Button2Click(Sender: TObject); 
begin 
  try
    Memo1.Lines.Text := IdHTTP1.Get('http://api.stackoverflow.com/0.8/stats/?Key=BadOnPurpose'); 
  except
    on E: EIdHTTPProtocolException do begin
      if E.ErrorCode = 400 then
        Memo1.Lines.Text := E.ErrorMessage
      else
        raise;
    end;
  end;
end; 
like image 200
Remy Lebeau Avatar answered Oct 17 '22 00:10

Remy Lebeau