英文:
Delphi /w Indy 10: Get Content after ERROR 400 (idHTTP)
问题
我正在尝试绕过Indy idHTTP组件,并在GET/PUT/POST后有些问题在服务器响应不是200 OK的情况下检索服务器响应。即使我禁用了ProtocolException,Response.ResponseText和返回的StringStream仅显示400错误,而不显示服务器传输的内容。
我如何获取这些数据?
提前谢谢。
英文:
I am trying to get around the Indy idHTTP Component and have some issues retrieving the server response after a GET/PUT/POST if it's not 200 OK.
Even if I disable the ProtocolException, Response.ResponseText AND the reutrned StringStream only show the 400 Error but not the content the server transmitted.
How can I get that data???
thx in advance
答案1
得分: 1
为了避免在非2xx状态下由TIdHTTP
组件丢弃响应主体,您还需要在HttpOptions
中使用hoWantProtocolErrorContent
。不幸的是,即使在随 RAD Studio 帮助文件一起提供的帮助文件中,这些选项也没有得到充分记录(帮助→第三方帮助→Indy Library 帮助)。
要将响应主体作为字符串获取,请使用返回字符串的Get
/Put
/Post
不变性,而不是TIdHTTP.Response.ResponseText
或简称为TIdHTTP.ResponseText
,其中包含HTTP响应的状态行,例如:HTTP/1.1 400 Bad Request
。
示例代码:
var
IdHTTP: TIdHTTP;
begin
IdHTTP := TIdHTTP.Create();
try
IdHTTP.HTTPOptions := IdHTTP.HTTPOptions + [hoNoProtocolErrorException, hoWantProtocolErrorContent];
Writeln(IdHTTP.ResponseText);
Writeln;
Writeln(IdHTTP.Get('https://postman-echo.com/status/400'));
finally
IdHTTP.Free;
end;
end;
示例输出:
HTTP/1.1 400 Bad Request
{"status":400}
英文:
To avoid discarding response body by TIdHTTP
component in case of non-2xx status, you'd also need to use hoWantProtocolErrorContent
among HttpOptions
. Unfortunatelly these options are poorly documented even in help file shipped with RAD Studio help (<kbd>Help</kbd>→<kbd>Third-Party Help</kbd>→<kbd>Indy Library Help</kbd>).
To get the response body as a string use Get
/Put
/Post
invariant that returns string, not TIdHTTP.Response.ResponseText
or TIdHTTP.ResponseText
for short which contains status line of HTTP response; e.g.: HTTP/1.1 400 Bad Request
.
Sample code:
var
IdHTTP: TIdHTTP;
begin
IdHTTP := TIdHTTP.Create();
try
IdHTTP.HTTPOptions := IdHTTP.HTTPOptions + [hoNoProtocolErrorException, hoWantProtocolErrorContent];
Writeln(IdHTTP.ResponseText);
Writeln;
Writeln(IdHTTP.Get('https://postman-echo.com/status/400'));
finally
IdHTTP.Free;
end;
end;
Sample output:
>HTTP/1.1 400 Bad Request
>
>{"status":400}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论