TIdHTTP返回的JSON无法解码

时间:2018-03-19 12:43:17

标签: json delphi idhttp

我有以下代码:

    var
      MemoryStream1: TMemoryStream;
      IdHTTP1: TIdHTTP;
      Bytes1: TBytes;
      s1: string;
    begin             
      IdHTTP1 := TIdHTTP.Create(nil);
      MemoryStream1 := TMemoryStream.Create;
      IdHTTP1.Get('https://restcountries.eu/rest/v2/all', MemoryStream1);
      MemoryStream1.Position := 0;
      MemoryStream1.SaveToFile('C:\Temp\MemoryStream1.txt');
      MemoryStream1.Position := 0;
      SetLength(Bytes1, MemoryStream1.Size);
      MemoryStream1.Read(Bytes1[0], MemoryStream1.Size);
      s1 := TEncoding.UTF8.GetString(Bytes1);

它在最后一行失败,并显示消息“目标多字节代码页中的unicode字符没有映射”

但是,我可以在HttpAnalyzer中清楚地看到返回的JSON。

文件'C:\ Temp \ MemoryStream1.txt'以十六进制'1F8B0800000000000003DC9BED6F1BB7'开头,当我期待与{ - 左括号 - 作为第一个字符

相对应的内容时

当我尝试     s1:= TEncoding.Unicode.GetString(Bytes1);

字符串s1包含“中文”字符。

1 个答案:

答案 0 :(得分:-1)

我解决了这个问题。显然,gzip没有解压缩。一个人必须自己做。这是:

    var
      IdHTTP1: TIdHTTP;
      a1: AnsiString;
      s1: string;
      MemoryStream1, MemoryStream2: TMemoryStream;
    begin             
      Screen.Cursor := crHourGlass;
      IdHTTP1 := TIdHTTP.Create(nil);
      MemoryStream1 := TMemoryStream.Create;
      MemoryStream2 := TMemoryStream.Create;
      IdHTTP1.Get('https://restcountries.eu/rest/v2/all', MemoryStream1);
      MemoryStream1.Position := 0;
      IdCompressorZLib1.DecompressGZipStream(MemoryStream1, MemoryStream2);
      FreeAndNil(MemoryStream1);
      MemoryStream2.Position := 0;
      SetLength(a1, MemoryStream2.Size);
      MemoryStream2.Read(a1[1], MemoryStream2.Size);   
     //  AnsiString a1 now contains the decompressed data