【问题标题】:Reading unicode strings from content fields of TWebRequest从 TWebRequest 的内容字段中读取 unicode 字符串
【发布时间】:2012-01-20 12:08:38
【问题描述】:

我们如何从 TWebRequest 的内容字段中检索实际的 unicode 字符串。当我尝试读取 TWebRequest 的内容字段以获取我在文本中输入的输入 unicode 值时,我看到的是乱码值而不是实际值。 我给出的输入是Добро,但在内容字段中我看到了值 С”С¾С±Ñ€С¾。响应内容类型设置为 text/html 和 charset='UTF-8'。 任何机构都可以告诉它为什么不显示在文本框中输入的实际值以及如何更正。

我正在测试的示例代码

procedure TWebModule1.WebModule1HelloAction(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
  s : string;
  PageProducer1 : TPageProducer;
begin
  Response.ContentType := 'text/html;charset=UTF-8';
  s := Request.ContentFields.Text;
  PageProducer1 := TPageProducer.Create(nil);
  try
    PageProducer1.HTMLFile := 'C:\Hello.tmpl';
    PageProducer1.OnHTMLTag := PageProducer1HTMLTag;
    Response.Content := PageProducer1.Content + ' ' + 'Entered string:' + s;
  finally
    PageProducer1.Free;
  end;
end;

Hello.tmpl 只有文本框和提交按钮

【问题讨论】:

    标签: delphi web-applications unicode delphi-xe2


    【解决方案1】:

    您可以使用UTF8ToString 函数将您的UTF-8 字符串转换为UnicodeString

    【讨论】:

    • 感谢您的回复,UTF8ToString 可以完美运行,但是由于 charset 设置为 UTF-8,字符串是 ut8 编码的,我们需要转换为 unicode 字符串。有什么方法或设置可以在 Request 对象上设置,以便它自动进行转换
    • HTTP 负载是任意八位字节序列。内容类型(和内容编码)字段告诉您如何解释它。读取正确的标头字段并以正确的方式处理有效负载是您的应用程序的责任。
    • 这将正常工作,但会发出警告W1058 隐式字符串转换,可能会丢失从'string'到'RawByteString'的数据。将它与使用 RawContent 而不是 Content 结合起来,警告就消失了。
    【解决方案2】:

    您只需要使用TWebRequest.ContentRaw,它会根据请求标头中定义的字符集返回具有正确代码页的 AnsiString。不幸的是,您将不得不手动处理内容。

    如果您确定字符集是 UTF-8,则要获取字符串 (UnicodeString),请使用 TEncoding.UTF8.GetString(BytesOf(Request.RawContent))。或者,您可以使用以下命令检查标头的原始 contentType:

    var ct: string;
    ...
    ct := string(Request.GetFieldByName('Content-type')).ToUpper;
    if (Pos('CHARSET', ct) > 0) and (Pos('UTF-8', ct) > 0) then
        Result := TEncoding.UTF8.GetString(BytesOf(Request.RawContent))
      else
        Result := TEncoding.ANSI.GetString(BytesOf(Request.RawContent));
    

    TWebRequest.ContentTWebRequest.ContentFields 在我当前版本的 () 中存在漏洞。它们始终以 ANSI 编码。 TWebRequest.EncodingFromContentType 尝试从 TWebRequest.ContentType 中提取字符集,但此时 contentType 中的字符集部分已被之前的代码删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      相关资源
      最近更新 更多