我遇到编码问题。当我得到网站的源代码时,我有:
我将编码设置为UTF8,如下所示:
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string sourceCode = reader.ReadToEnd();
感谢您的帮助!
答案 0 :(得分:6)
尝试使用指定的编码:
Encoding encoding;
try
{
encoding = Encoding.GetEncoding(response.CharacterSet);
}
catch (ArgumentException)
{
// Cannot determine encoding, use dafault
encoding = Encoding.UTF8;
}
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;
答案 1 :(得分:2)
但响应可能不是UTF-8。您是否检查了响应对象的CharacterSet
和ContentType
属性,以确保使用正确的编码?
无论如何,对于值03和08,这两个字符看起来像代码页437个字符。看起来数据流中有一些二进制数据。
我建议你进行调试,使用Stream.Read
将响应中的前几个字节读入一个字节数组,然后检查这些值,看看你得到了什么。
答案 2 :(得分:1)
我有同样的问题,我尝试改变编码,从源头到结果,我什么也没得到。最后我遇到一个线索,引导我跟随...... 看看这里...... .NET: Is it possible to get HttpWebRequest to automatically decompress gzip'd responses?
在从请求中检索响应之前,您需要使用以下代码。
rqst.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
因为一旦我们使用接受编码' gzip'或者' deflate',数据被压缩,并转向我们无法读取的数据。所以我们需要解压缩它们。
答案 3 :(得分:0)
在代码中更改此行:
using (StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding(1251)))
它可能对你有所帮助..