在 Delphi 中获取非 ASCII 字符到 WebBroker 响应中

Kev*_*son 2 delphi utf-8 webbroker delphi-xe4

我有一个带有 nvarchar 数据的 MS SQL Server 数据库,特别是一个带有“?ABC?”的数据字段。在里面。我的 Delphi 桌面应用程序显示得很好,但是来自 Delphi XE4 中使用 TDataSetTableProducer 生成响应的 WebBroker 应用程序的相同数据不起作用。这是基本的示例代码:

procedure TWebModule1.WebModule1TestAction(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
  Response.ContentEncoding := 'text/plain; charset="UTF-8"';
  Response.Content := '<!DOCTYPE html>'
  + '<html>'
  + '<body>'
  + '<p> ?ABC? </p>'
  + '</body>'
  + '</html>'
end;
Run Code Online (Sandbox Code Playgroud)

在网络浏览器中查看时,结果是“?ABC?”。我尝试了很多东西(包括 UTF-16 和用 Char($FEFF) 作为响应前缀),但没有任何帮助。这样做的正确方法是什么?

Rem*_*eau 6

'text/plain; charset="UTF-8"'不是该Response.ContentEncoding属性的有效值。你需要把它放在Response.ContentType属性中。此外,它应该使用text/html而不是text/plain

Response.ContentType := 'text/html; charset="UTF-8"';
Run Code Online (Sandbox Code Playgroud)

如果浏览器仍然无法正确显示数据,您可能必须使用Response.ContentStream属性而不是Response.Content属性,因此您可以自己对 UTF-8 数据进行编码:

procedure TWebModule1.WebModule1TestAction(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
  Response.ContentType := 'text/html; charset="UTF-8"';
  Response.ContentStream := TStringStream.Create(
    '<!DOCTYPE html>'
    + '<html>'
    + '<body>'
    + '<p> ?ABC? </p>'
    + '</body>'
    + '</html>',
    TEncoding.UTF8);
end;
Run Code Online (Sandbox Code Playgroud)

  • Response.ContentType := 'text/html; 字符集="UTF-8"'; 成功了。流媒体是没有必要的。请注意,有必要在设置 Content 之前设置 ContentType。 (2认同)