如何以正确的字符串形式获取 httpWebresponse 的内容?
有时我会从几个网站收到一些乱码的响应。
这是我的代码:
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??}y?F??????Z??????{7m???oX?\r?Y? ??33??d;y?????n?0?
我应该如何克服这个问题?和编码有关吗?
Sometimes I am getting kind of garbled response from several web sites.
Here is my code:
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
}
when I request from www.google.co.in I get following characters in resp string:
?\b\0\0\0\0\0??}y?F?????????Z??????{7m???oX?\r?Y???33??d;y????n?0?
How should I overcome this problem? Is it related to encoding?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我收到的响应是 GZip 压缩的,因此我只是解压缩响应流,如下所示:
现在可以使用我上面提供的代码读取该流。
@Kalyan 感谢您的帮助!
The response I received was GZip-compressed, so I just decompressed the response stream as shown below:
now one can read the stream using the code I provided above.
@Kalyan Thanks for your help!!!
请参阅如何在 C# 中使用 GetResponseStream 方法 以及 HttpWebResponse 和HttpWebRequest 用于了解如何从 HttpWebResponse 读取内容。希望它能帮助你。
Refer to How to use the GetResponseStream method in C# and also Usage of HttpWebResponse and HttpWebRequest for getting an idea about reading contents from HttpWebResponse. Hope it will help you.