Delphi /w Indy 10: 获取ERROR 400后的内容 (idHTTP)

huangapple go评论91阅读模式
英文:

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(&#39;https://postman-echo.com/status/400&#39;));
  finally
    IdHTTP.Free;
  end;
end;

Sample output:
>HTTP/1.1 400 Bad Request
>
>{"status":400}

huangapple
  • 本文由 发表于 2020年1月3日 18:00:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定