0

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

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

有些东西是错的,但我不知道在哪里。有任何想法吗?

4

1 回答 1

5

问题是,当您获得数据时,它已经被转换了。

执行时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);
于 2013-10-14T16:31:05.217 回答