Delphi XE2:UTF16LE - > UTF8

时间:2012-05-14 06:30:18

标签: delphi unicode utf-8 delphi-xe2 indy

网址:http://www.gagalive.kr/livechat1.swf?chatroom=~~~BBQ

[1] -------------------------------------------- -----------------------

procedure TForm1.FormCreate(Sender: TObject);

begin

 IdTCPClient.Host := '61.97.246.131';

  IdTCPClient.Port := 8080;

  IdTCPClient.Connect;

  IdTCPClient.IOHandler.Write('Ag8m' + Char(0));

  IdTCPClient.IOHandler.Write('LShady|###BBQ' + Char(0));

  IdTCPClient.IOHandler.Write('#' + 'Some Text'  + Char(0));

  IdTCPClient.Disconnect;

end;

[2] -------------------------------------------- -----------------------

function UTF8FromUTF16_2(sUTF16: UnicodeString): UTF8String; 

begin   

  Result := sUTF16; 

end; 

procedure TForm1.FormCreate(Sender: TObject);

begin

 IdTCPClient.Host := '61.97.246.131';

  IdTCPClient.Port := 8080;

  IdTCPClient.Connect;

  IdTCPClient.IOHandler.Write('Ag8m' + Char(0));

  IdTCPClient.IOHandler.Write('LShady|###BBQ' + Char(0));

  IdTCPClient.IOHandler.Write(UTF8FromUTF16_2('#' + '안녕'  + Char(0)));

  IdTCPClient.Disconnect;

end;

[1]:工作

[2]:不工作(字符串坏了> Shady:??)

请参阅:http://www.gagalive.kr/livechat1.swf?chatroom=~~~BBQ

UTF8FromUTF16函数原始VB代码:VB 6.0 -> Delphi XE2 Conversion

帮助我...... :(

1 个答案:

答案 0 :(得分:3)

字符串在XE2中以UTF-16编码。 #2不起作用,因为您传递UTF8String,其中UnicodeString是预期的,因此RTL将执行UTF-8 - > Indy看到数据之前的UTF-16转换,然后Indy会在传输过程中将UTF-16数据转换为自己的默认编码。

如果你想将UnicodeString作为UTF-8传输,你必须通过其TIdTextEncoding类告诉Indy这样做,例如:

procedure TForm1.FormCreate(Sender: TObject); 
begin 
  IdTCPClient.Host := '61.97.246.131'; 
  IdTCPClient.Port := 8080; 
  IdTCPClient.Connect; 
  IdTCPClient.IOHandler.Write('Ag8m'#0); 
  IdTCPClient.IOHandler.Write('LShady|###BBQ'#0); 
  IdTCPClient.IOHandler.Write('#안녕'#0, TIdTextEncoding.UTF8); // <-- here
  IdTCPClient.Disconnect; 
end; 

或者:

procedure TForm1.FormCreate(Sender: TObject); 
begin 
  IdTCPClient.Host := '61.97.246.131'; 
  IdTCPClient.Port := 8080; 
  IdTCPClient.Connect; 
  IdTCPClient.IOHandler.DefStringEncoding := TIdTextEncoding.UTF8; // <-- here
  IdTCPClient.IOHandler.Write('Ag8m'#0); 
  IdTCPClient.IOHandler.Write('LShady|###BBQ'#0); 
  IdTCPClient.IOHandler.Write('#안녕'#0);
  IdTCPClient.Disconnect; 
end; 

如果您没有告诉Indy使用哪种编码,它将默认为ASCII,这将损坏/丢失您的Unicode数据。