从TIdHttp获取响应,错误代码为400 [英] Getting Response from TIdHttp with Error Code 400

查看:310
本文介绍了从TIdHttp获取响应,错误代码为400的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为 StackApps API编写Delphi库。



我有遇到印地问题。我正在使用Delphi 2010附带的版本。
如果将无效参数传递给其中一个StackApps API,它将返回HTTP错误代码400,然后在响应中它将包含带有更多详细信息的JSON对象。 / p>

通过访问 http:/ /api.stackoverflow.com/0.8/stats/?Key=BadOnPurpose 在Chrome浏览器中,您可以看到一个示例。即



使用WireShark,我可以看到使用下面的代码返回了JSON对象,但是我无法使用Indy来访问它。

>

对于此测试代码,我在窗体上放置了一个TIdHttp组件,并将以下代码放置在按钮中。

 过程TForm10.Button2Click(Sender:TObject); 
var
SS:TStringStream;
开始
SS:= TStringStream.Create;
IdHTTP1.Get(’http://api.stackoverflow.com/0.8/stats/?Key=BadOnPurpose’,SS,[400]);
Memo1.Lines.Text:= SS.DataString;
SS。免费;
结尾;

我通过了[400],因此不会引发400例外。好像Indy停止读取响应。由于Memo1的内容为空。



我正在寻找一种获取JSON详细信息的方法。

解决方案

从对Get()的调用中删除AIgnoreReplies参数值。让它正常引发异常。您要查找的JSON文本位于EIdHTTPProtocolException.ErrorMessage属性中。例如:

 过程TForm10.Button2Click(Sender:TObject); 
开始
尝试
Memo1.Lines.Text:= IdHTTP1.Get(’http://api.stackoverflow.com/0.8/stats/?Key=BadOnPurpose’);
在E:EIdHTTPProtocolException上的
除外,如果E.ErrorCode = 400,则开始
,然后
Memo1.Lines.Text:= E.ErrorMessage
否则
加注;
结尾;
结尾;
结尾;


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.

解决方案

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; 

这篇关于从TIdHttp获取响应,错误代码为400的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆