5

I'm trying to get json response via HTTP GET method to a string but all I got is that: enter image description here

I'm using a code like that:

memo1.Text:= idhttp1.Get('http://blabla.com/bla.php');

it returns json data. i need to get that json response to memo1.

How can I do that?

Someone
  • 728
  • 2
  • 12
  • 23
  • Check the encoding of the text that you receive (should be in the headers somewhere) and apply the appropriate translation/conversion, ie UTF-8 to Ansi as you are using a non-Unicode Delphi. Searching for these terms should bring up plenty of examples. – Marjan Venema Mar 27 '13 at 07:13
  • 1
    @MarjanVenema: The overloaded version of `TIdHTTP.Get()` that returns a String already does exactly that. – Remy Lebeau Mar 27 '13 at 17:56

2 Answers2

5

I found a solution. That code works perfect.

function GetURLAsString(aURL: string): string;
var
  lHTTP: TIdHTTP;
  lStream: TStringStream;
begin
  lHTTP := TIdHTTP.Create(nil);
  lStream := TStringStream.Create(Result);
  try
    lHTTP.Get(aURL, lStream);
    lStream.Position := 0;
    Result := lStream.ReadString(lStream.Size);
  finally
    FreeAndNil(lHTTP);
    FreeAndNil(lStream);
  end;
end;
Someone
  • 728
  • 2
  • 12
  • 23
  • there's a way to suppress the dialog errors and get the errors as text? it you try to `GetURLAsString('http://google.com')` a dialog pops `301 moved permanently` – Vitim.us Apr 25 '13 at 02:28
2

Try a newer version of Indy, Indy still supports non-Unicode Delphi.

The Indy TIdHTTP Get should automatially convert UTF-8 to Ansi (with limitations):

Internally, TIdHTTP.Get() decodes the server's UTF-8 data to Unicode, and then converts that to Ansi when returning it as an AnsiString in pre-2009 versions. That AnsiString uses the OS's default Ansi codepage, so yes, there is potential for data loss if the OS's current language does not support the Unicode characters being used by the server. http://forums2.atozed.com/viewtopic.php?f=7&t=3011

mjn
  • 36,362
  • 28
  • 176
  • 378