我开发了通过HTTP进行通信的服务器和移动客户端。服务器是用 Delphi 7 编写的(因为它必须与旧代码兼容),客户端是用 XE6 编写的移动应用程序。服务器向客户端发送包含字符串的数据流。一个问题与编码有关。
在服务器上,我尝试以UTF8传递字符串:
//Writes string to stream
procedure TStreamWrap.WriteString(Value: string);
var
BytesCount: Longint;
UTF8: string;
begin
UTF8 := AnsiToUtf8(Value);
BytesCount := Length(UTF8);
WriteLongint(BytesCount); //It writes Longint to FStream: TStream
if BytesCount > 0 then
FStream.WriteBuffer(UTF8[1], BytesCount);
end;
因为它是用 Delphi7 编写的,所以 Value 是一个单字节字符串。
在客户端上,我以UTF8读取字符串并将其编码为Unicode
//Reads string from current position of stream
function TStreamWrap.ReadString: string;
var
BytesCount: Longint;
UTF8: String;
begin
BytesCount := ReadLongint;
if BytesCount = 0 then
Result := ''
else
begin
SetLength(UTF8, BytesCount);
FStream.Read(Pointer(UTF8)^, BytesCount);
Result := UTF8ToUnicodeString(UTF8);
end;
end;
但它不起作用,当我显示带有ShowMessage
字母的字符串时是错误的。那么如何在Delphi 7中存储字符串并在移动应用程序上的XE6中恢复呢?我应该在表示字符串的数据的开头添加BOM吗?