Delphi中IdHttp组件异常非200获取返回JSON数据

参考原文:https://www.atozed.com/forums/thread-771.html?highlight=400+Bad+Request

另外还有一篇文章说明也可参考 http://www.sumweb.net/archives/1666

 

使用您显示的确切代码,我没有收到“ HTTP / 1.1 400 错误的 请求”响应。我收到“ HTTP / 1.1 400 ”(没有“错误 请求”)响应。但更重要的是,响应正文包含以下JSON文档:

码:
{"error":"invalid_grant","error_description":"The user name or password is incorrect."}


您可以通过捕获引发的EIdHTTPProtocolException并读取其ErrorMessage属性来访问该JSON 

码:
try
 Result := lHTTP.Post(HttpAutenticazione+‘/auth/signin‘, lParamList);
except
 on E: EIdHTTPProtocolException do begin
   // use E.ErrorMessage as needed...
 end
end;


或者,您可以启用TIdHTTP的hoNoProtocolErrorExceptionhoWantProtocolErrorContent标志,然后Post()将不会引发EIdHTTPProtocolException,并且返回的字符串将为JSON:

码:
lHTTP.HTTPOptions := lHTTP.HTTPOptions + [hoNoProtocolErrorException, hoWantProtocolErrorContent];
Response := lHTTP.Post(HttpAutenticazione+‘/auth/signin‘, lParamList);
if (lHTTP.ResponseCode div 100) <> 2 then
begin
 // use Response as needed...
end else
 Result := Response;
 
 

Delphi中IdHttp组件异常非200获取返回JSON数据

上一篇:常用的Windows快捷键


下一篇:AcWing 717.简单斐波那契