有时我会从几个网站上得到一些乱码回复。
这是我的代码:
Stream responseStream = response.GetResponseStream();
buffer = new Byte[256];//
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
outStream.Write(buffer, 0, bytesRead);
//resp=resp+ .UTF8.GetString(buffer, 0, bytesRead);
resp=resp + Encoding.ASCII.GetString(buffer); //resp is string
}
当我从www.google.co.in请求时,我会在resp字符串中找到以下字符:
?\ B \ 0 \ 0 \ 0 \ 0 \ 0ερ}ÿ·F ?????????Ž?????? {7米??? OX吗?\ r?Y' ?? 33 ?? d;?ý???? N 0
我该如何克服这个问题?它与编码有关吗?
答案 0 :(得分:6)
我收到的回复是GZip压缩的,所以我只是解压缩了响应流,如下所示:
Stream responseStream = response.GetResponseStream();
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
现在可以使用我上面提供的代码读取流。
@Kalyan感谢您的帮助!!!
答案 1 :(得分:3)
有关从HttpWebResponse读取内容的想法,请参阅How to use the GetResponseStream method in C#和Usage of HttpWebResponse and HttpWebRequest。希望它会对你有所帮助。