我要下载一个用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有些事情不对劲,但我找不到地方。有什么想法吗?
发布于 2013-10-14 16:31:05
问题是,当你得到数据时,它已经被转换了。
当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标头中指定的编码来解释字符串,那么您必须下载原始字节,确定编码,并使用它来解释字符串。例如:
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);https://stackoverflow.com/questions/19363249
复制相似问题