【问题标题】:Why UTF-8 fail on this encoding?为什么 UTF-8 在这种编码上失败?
【发布时间】:2013-10-14 15:03:07
【问题描述】:

我即将下载一个以 UTF-8 编码的page。 所以这是我的代码:

using (WebClient client = new WebClient())
{
    client.Headers.Add("user-agent", Request.UserAgent);

    htmlPage = client.DownloadString(HttpUtility.UrlDecode(resoruce_url));

    var KeysParsed = HttpUtility.ParseQueryString(client.ResponseHeaders["Content-Type"].Replace(" ", "").Replace(";", "&"));
    var charset = ((KeysParsed["charset"] != null) ? KeysParsed["charset"] : "UTF-8");
    Response.Write(client.ResponseHeaders);

    byte[] bytePage = Encoding.GetEncoding(charset).GetBytes(htmlPage);
    using (var reader = new StreamReader(new MemoryStream(bytePage), Encoding.GetEncoding(charset)))
    {
        htmlPage = reader.ReadToEnd();
        Response.Write(htmlPage);
    }
}

所以,它为编码设置了UTF-8。但是下载的标题,例如,在我的屏幕上显示为:

Sexy cover: 60 e più di “quei dischi” vietati ai minori

而不是:

Sexy cover: 60 e più di “quei dischi” vietati ai minori

出了点问题,但我不知道在哪里。有什么想法吗?

【问题讨论】:

  • 如果您使用网络浏览器会显示什么?
  • 使用网络浏览器时,标题上的正确文本是Sexy cover: 60 e più di “quei dischi” vietati ai minori。试试自己,用 Firefox 打开它:)
  • “性感封面”。先生,我在上班。试试 UTF-16 和 ASCII 西欧,看看它是怎么说的。你确定你应该默认为 UTF-8 吗?
  • 另外,是否有任何标题可以告诉您编码是什么?
  • var KeysParsed = HttpUtility.ParseQueryString(client.ResponseHeaders["Content-Type"].Replace(" ", "").Replace(";", "&")); 这段代码应该做什么?

标签: c# encoding utf-8


【解决方案1】:

问题是当你得到数据时它已经被转换了。

WebClient.DownloadString 执行时,它会获取原始字节并使用默认编码将它们转换为字符串。损坏已完成。您不能将生成的字符串转换回字节,然后重新解释它。

换句话说,这就是正在发生的事情:

// WebClient.DownloadString does, essentially, this.
byte[] rawBytes = DownloadData();
string htmlPage = Encoding.Default.GetString(rawBytes);

// Now you're doing this:
byte[] myBytes = Encoding.Utf8.GetBytes(htmlPage);

myBytes 不一定与rawBytes 相同。

如果您事先知道要使用什么编码,则可以设置WebClient 实例的Encoding 属性。如果要根据 Content-Type 标头中指定的编码来解释字符串,则必须下载原始字节,确定编码并使用它来解释字符串。例如:

var rawBytes = client.DownloadData(HttpUtility.UrlDecode(resoruce_url));
var KeysParsed = HttpUtility.ParseQueryString(client.ResponseHeaders["Content-Type"].Replace(" ", "").Replace(";", "&"));
var charset = ((KeysParsed["charset"] != null) ? KeysParsed["charset"] : "UTF-8");

var theEncoding = Encoding.GetEncoding(charset);
htmlPage = theEncoding.GetString(rawBytes);

【讨论】:

  • 啊,有GetString(),所以我根本不需要GetBytes!谢谢你!
猜你喜欢
  • 1970-01-01
  • 2019-05-29
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-01
相关资源
最近更新 更多