zac
zac

Reputation: 4918

How to read response from Indy IdHTTP get

I have written code to use get with indy IdHTTP component

var
get_url: string;
resp: TMemoryStream;
begin
  get_url := 'http://localhost/salesapp/is_run.php?ser=';
  resp := TMemoryStream.Create;

  IdHTTP1.Get(get_url+'v', resp);
  memo1.Lines.LoadFromStream(resp);

This url http://localhost/salesapp/is_run.php?ser=v return JSON response but I dont know how to read it from Delphi.

Upvotes: 3

Views: 35423

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598309

When Get() exits, the stream's Position is at the end of the stream. You need to reset the Position back to 0 before calling LoadFromStream(), or else it will not have anything to load:

var
  get_url: string;
  resp: TMemoryStream;
begin
  get_url := 'http://localhost/salesapp/is_run.php?ser=';
  resp := TMemoryStream.Create;
  try
    IdHTTP1.Get(get_url+'v', resp);
    resp.Position := 0; // <-- add this!!
    memo1.Lines.LoadFromStream(resp);
  finally
    resp.Free;
  end;
end;

The alternative is to remove the TMemoryStream and let Get() return the JSON as a String instead:

memo1.Text := IdHTTP1.Get(get_url+'v');

Upvotes: 15

Related Questions