我使用TidHTTP.Post将JSON发送到restful服务,但在发生HTTP400错误时无法读取来自idHTTP的响应。当出现400时,服务器提供JSON,它描述发送的数据中的错误。我有时会得到可读的JSON结果,但大多数情况下,响应只包含几个不可打印的字符。
procedure TForm1.SendData(const stlACSchedule: TStringList; BatchTimeIn: TDateTime);
var
TargetURL : String;
stsJson: TStringStream;
myResponse : String;
resp : TMemoryStream;
begin
TargetURL := 'http://sandbox.xxxxxxxxxxx.com/api/v1/feeds' ;
stsJson := TStringStream.Create;
stsJson.WriteString(stlACSchedule.Text);
resp := TMemoryStream.Create;
application.ProcessMessages;
try
myResponse := IdHTTP1.Post( TargetURL, stsJson );
WriteStatus( 'Response from Vendor Server: ' );
UpdateUploadStatus2( IdHTTP1.ResponseCode, IdHttp1.ResponseText, BatchTimeIn, 'usPending', 'usUploaded' );
except
on E: EIdHTTPProtocolException do begin
WriteStatus( 'HTTP Protocol Error from Vendor Server: ' + #13 + E.ErrorMessage + ' -*- ' + IdHTTP1.ResponseText );
UpdateUploadStatus2( IdHTTP1.ResponseCode, E.ErrorMessage + ' - ' + IdHTTP1.ResponseText, BatchTimeIn, 'usPending', 'usBatchFail' );
ShowMessage('Fubar_!: ' + myResponse);
end;
on E: Exception do begin
WriteStatus( 'Unknown Error from Vendor Server:' );
UpdateUploadStatus2( IdHTTP1.ResponseCode, E.Message + ' - ' + IdHTTP1.ResponseText, BatchTimeIn, 'usPending', 'usBatchFail' );
ShowMessage('Fubar!: ' + myResponse);
end;
end;
resp.free;
stsJson.free;
end; { SendData }
procedure TForm1.WriteStatus(strTextIn : String);
begin
Memo1.Lines.add('');
Memo1.Lines.add(strTextIn);
Memo1.Lines.add(IntToStr(IdHTTP1.ResponseCode));
Memo1.Lines.add(IdHTTP1.ResponseText);
end; { WriteStatus }看起来EIdHTTPProtocolException异常处理程序正在捕获错误,但大多数时候我会得到这样的响应(在“来自供应商服务器的HTTP协议错误”行下面有3个不可打印的字符):
HTTP Protocol Error from Vendor Server:
400
HTTP/1.1 400 Bad Request但偶尔我会得到一个很好的响应,比如:
HTTP Protocol Error from ReturnJet Server:
{"errors":[{"code":7,"message":"Invalid departure or destination type for event: 1"}]} -*- HTTP/1.1 400 Bad Request
400
HTTP/1.1 400 Bad Request它看起来可能与响应的长度有关,但我不确定。
我需要做什么才能一致地解码ResponseText?
我使用的是: Delphi XE8,Indy10.6版本
PS -当我使用Postman手动发布这些数据时,我总是得到完整的JSON响应。
提亚
发布于 2018-02-28 04:27:48
400响应是错误响应。缺省情况下,当发生HTTP错误时(除非您要求它不这样做),TIdHTTP会引发EIdHTTPProtocolException异常,其中HTTP响应头在TIdHTTP.Response属性中可用,HTTP响应内容在异常的ErrorMessage属性中作为string可用,这样就不会破坏用于输出的任何TStream (除非您请求它)。
如果异常的ErrorMessage不包含您期望的JSON,则可能是服务器一开始就没有发送JSON,或者JSON没有以Indy可以解码为string的格式传输。但是您没有显示实际的HTTP响应是什么样子,或者"3个不可打印的字符“实际上是什么,所以没有办法确切地知道为什么ErrorMessage没有像您期望的那样被填充。
发布于 2019-01-31 01:35:30
你必须更改IdHTTP上的一些选项,才能得到与浏览器或邮递员之类的程序相同的响应。
使用:
IdHTTP1.HTTPOptions := idHTTP1.HTTPOptions + [hoNoProtocolErrorException, hoWantProtocolErrorContent];https://stackoverflow.com/questions/49016689
复制相似问题