我有编码问题。当我得到网站的源代码,我有: HttpWebResponse - 编码问题
我设置编码UTF8这样的:
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string sourceCode = reader.ReadToEnd();
感谢您的帮助!
我有编码问题。当我得到网站的源代码,我有: HttpWebResponse - 编码问题
我设置编码UTF8这样的:
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string sourceCode = reader.ReadToEnd();
感谢您的帮助!
但是,响应可能不是UTF-8。您是否检查过响应对象的CharacterSet
和ContentType
属性以确保您使用正确的编码?
在任何情况下,这两个字符看起来都像代码页437个字符,用于值03和08.它看起来像是数据流中有一些二进制数据。
我建议,为了调试,您使用Stream.Read
将响应中的前几个字节读取到字节数组中,然后检查值以查看所得结果。
尝试使用指定的编码:
Encoding encoding = Encoding.UTF8;
try
{
if (response != null && !string.IsNullOrEmpty(response.CharacterSet))
encoding = Encoding.GetEncoding(response.CharacterSet);
}
catch (ArgumentException)
{
// Cannot determine encoding, use assigned above
}
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
string sourceCode = reader.ReadToEnd();
如果您接受gzip的莫名其妙,这可能会帮助:(还没有尝试过自己,诚然它并没有太大的意义,因为你的编码不gzip的?!)
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
更改这一行代码:
using (StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding(1251)))
它可以帮助你..
我有同样的问题,我试着改变编码,从源头到结果,我什么都没有。在最后,我遇到一个线程这导致我下面...... 采取看看这里... .NET: Is it possible to get HttpWebRequest to automatically decompress gzip'd responses?
你需要使用下面的代码,从检索请求的响应之前。
rqst.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
,因为一旦我们使用接受编码“的gzip”或“放气”,数据得到了压缩,而转向由我们不可读的数据。所以我们需要解压缩它们。
您确定您从流中获取的数据具有UTF8编码吗?它似乎不是真的 – 2011-04-22 13:08:28
我使用萤火虫来检查编码。 Content-Type:text/html; charset = UTF-8 – carck3r 2011-04-22 14:40:34
我不得不使用Accept-Encoding标头注释此行。有用。 – carck3r 2011-05-03 13:25:39