delphi 如何对TIdHTTP调用的响应进行编码?

lo8azlld  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(226)

在一个项目中,我使用TIDHTTP来调用Web服务器。
The webserver is an asp.net test application that returns the following json:

{
   "message":"test ÀÈÉÌÒÙàèéìòù"
}

我在Delphi中得到的响应是一种未编码的字符串:
{"message":"test ÃÃÃÃÃÃàèéìòù"}
这是我如何使用TIDHTTP:

Result := '';
  IdHTTP := TIdHTTP.Create;
  IdHTTP.Request.MethodOverride := 'ForwardCommand';
  IdSSLIOHandlerSocketOpenSSL :=  TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP);
  IdSSLIOHandlerSocketOpenSSL.SSLOptions.Mode       := sslmClient;
  IdSSLIOHandlerSocketOpenSSL.SSLOptions.SSLVersions:= [sslvTLSv1_2];
  IdHTTP.IOHandler := IdSSLIOHandlerSocketOpenSSL;
  IdHTTP.HandleRedirects := True;
  IdHTTP.Response.ContentEncoding := 'UTF-8'; // I tried this but it seems not enough! 
  try
    url := 'testappUrl';
    try
      IdHTTP.ConnectTimeout := 2000; 
      IdHTTP.ReadTimeout := 4000; 
      Response := IdHTTP.Get(url);
      ShowMessage(response);
    except
      on E:Exception do
      begin
        response := StringReplace(E.Message,#10,' ',[rfReplaceAll]);
        response := StringReplace(response,#13,' ',[rfReplaceAll]);
        response := '{"errormessage": "'+response+'"}';
      end;
    end;
    Result := response;
  finally
    IdHTTP.Free;
  end;

请告诉我怎样才能正确地看到响应。2有没有一种方法可以强制编码以使重音字符被正确地读取?
谢谢。

66bbxpm5

66bbxpm51#

尝试使用TStringStream强制编码(UTF-8)。
测试以下代码以获得响应:

var
  ts:TStringStream;
begin

  ...

  ts := TStringStream.Create(string.Empty, TEncoding.UTF8);
  IdHTTP1.Get('url', ts);

  ShowMessage(ts.DataString);
    or
  ShowMessage(ts.ToString);
  ...

相关问题