Getting Response from TIdHttp with Error Code 400

筅森魡賤 提交于 2019-12-08 16:25:09

问题


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.


回答1:


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; 


来源:https://stackoverflow.com/questions/3018346/getting-response-from-tidhttp-with-error-code-400

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!