-2

How can I get the response text in Delphi's IdHTTP similar to JS ajax response? There is standard responseText property that contains page content, also IdHTTP has responseCode property, but it represents HTTP status code.

For example, in JS ajax response there are statusCode and responseText (see the image).

enter image description here

Jerry Dodge
  • 26,858
  • 31
  • 155
  • 327
  • This is custom API's repsonse code that returns 0 on normal request and negative number on error. –  Aug 24 '16 at 18:33
  • Question: Are you asking how to access the complete content in the response? Or are you asking how to parse this JSON which was received from the server? Is `-1` the *full* content received? Or is the JSON object the *full* content? – Jerry Dodge Aug 24 '16 at 19:53
  • 1
    The JSON is just an example of response which I get in JS using ajax. Delphi's ResponseText contains 'HTTP/1.1 400 incorrect-web-api-key' string. Ajax's responseText contains '-1'. I need to get '-1' in Delphi. –  Aug 25 '16 at 16:28
  • And did you see my answer down below which I posted almost one full day ago? – Jerry Dodge Aug 25 '16 at 17:33
  • Server does not response JSON. Related screenshot is a console.log of ajax repsonse object. –  Aug 25 '16 at 18:05
  • I'll ask again, did you read my answer? It tells you precisely how to get the response. But given this is the whole purpose of using such components, I'm rather disappointed that you couldn't just search for one of the thousands of topics. – Jerry Dodge Aug 25 '16 at 18:06
  • Delphi's IdHTTP.Get ResponseText is empty. Ajax response is on the related image. –  Aug 25 '16 at 18:24

2 Answers2

3

responseText in the XMLHttpRequest is equivalent to a response's "Content" in the Indy library. The call to TIdHTTP.Get offers a few different ways to obtain this content. The easiest is to just read the result of the Get function as a String...

var
  ResponseText: String;
begin
  ResponseText := IdHTTP1.Get('www.google.com');
  ...
end;

Depending on the content type, you may wish to use one of the other overloads of Get, for example one which can fill a TStream.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jerry Dodge
  • 26,858
  • 31
  • 155
  • 327
  • Yes, you need to download the JSON content first, using either `TIdHTTP.Get()` overload, and then you can parse the JSON to extract its `status` and `responseText` values. – Remy Lebeau Aug 24 '16 at 19:43
  • But what if `TIdHTTP.Get()` resulted in HTTP 400 Bad request? – ArieKanarie Feb 27 '20 at 16:14
2

Okay, I finally found the solution. To get that I used try ... catch operator and EIdHTTPProtocolException:

try
  Result := id_http.Post(url, params);
except
  on E: EIdHTTPProtocolException  do
    if (id_http.ResponseCode = 400) then
      Result := E.ErrorMessage
    else
      Result := E.Message;
end;

Sorry if my question was initially unclear.