如何将TIdBytes编码为Base64字符串(不是AnsiString)?

  ASocket.IOHandler.CheckForDataOnSource(5);

  if not ASocket.Socket.InputBufferIsEmpty then
  begin
    ASocket.Socket.InputBuffer.ExtractToBytes(data);
    // here I need to encode data to base64 string, how ? I don't need AnsiString!!
    // var s:string;
    s := EncodeBase64(data, Length(data)); // but it will be AnsiString :(


或者如何通过AContext.Connection.Socket.Write()发送AnsiString?

编译器说隐式字符串从'AnsiString'转换为'string'

“数据”变量包含来自网站的UTF-8数据。

最佳答案

您可以使用Indy的TIdEncoderMIME类将StringTStreamTIdByte数据编码为base64(和TIdDecoderMIME从base64解码回StringTStreamTIdBytes),例如:

s := TIdEncoderMIME.EncodeBytes(data);


至于发送AnsiString数据,D2009 +中的Indy根本没有用于处理TIdIOHandler.Write()数据的任何AnsiString重载,只有UnicodeString数据。要原样发送AnsiString,您可以:

1)使用AnsiStringTIdBytes复制到RawToBytes()中,然后调用TIdIOHandler.Write(TIdBytes)

var
  as: AnsiString;
begin
  as := ...;
  AContext.Connection.IOHandler.Write(RawToBytes(as[1], Length(as)));
end;


2)将AnsiString数据复制到TStream中,然后调用TIdIOHandler.Write(TStream)

var
  as: AnsiString;
  strm: TStream;
begin
  strm := TMemoryStream.Create;
  try
    strm.WriteBuffer(as[1], Length(as));
    AContext.Connection.IOHandler.Write(strm);
  finally
    strm.Free;
  end;
end;


要么:

var
  as: AnsiString;
  strm: TStream;
begin
  as := ...;
  strm := TIdMemoryBufferStream.Create(as[1], Length(as));
  try
    AContext.Connection.IOHandler.Write(strm);
  finally
    strm.Free;
  end;
end;

关于string - Delphi:如何将TIdBytes编码为Base64字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8484273/

10-12 23:07