HttpWebResponse 的编码问题 [英] Encoding trouble with HttpWebResponse

查看:29
本文介绍了HttpWebResponse 的编码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是代码片段:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(request.RawUrl);
WebRequest.DefaultWebProxy = null;//Ensure that we will not loop by going again in the proxy
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string charSet = response.CharacterSet;
Encoding encoding;
if (String.IsNullOrEmpty(charSet))
encoding = Encoding.Default;
else
encoding = Encoding.GetEncoding(charSet);

StreamReader resStream = new StreamReader(response.GetResponseStream(), encoding);
return resStream.ReadToEnd();

问题是如果我用以下方式测试:http://www.google.fr

The problem is if I test with : http://www.google.fr

所有é"显示效果不佳.我尝试将 ASCII 更改为 UTF8,但它仍然显示错误.我已经在浏览器中测试了 html 文件,并且浏览器可以很好地显示 html 文本,所以我很确定问题出在我用来下载 html 文件的方法中.

All "é" are not displaying well. I have try to change ASCII to UTF8 and it still display wrong. I have tested the html file in a browser and the browser display the html text well so I am pretty sure the problem is in the method I use to download the html file.

我应该改变什么?

删除了无效的 ImageShack 链接

推荐答案

首先,编写该代码的更简单方法是使用 StreamReader 和 ReadToEnd:

Firstly, the easier way of writing that code is to use a StreamReader and ReadToEnd:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(myURL);
using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
{
    using (Stream resStream = response.GetResponseStream())
    {
        StreamReader reader = new StreamReader(resStream, Encoding.???);
        return reader.ReadToEnd();
    }
}

然后只是"找到正确的编码的问题.你是如何创建文件的?如果它与记事本一起使用,那么您可能需要 Encoding.Default - 但这显然不可移植,因为它是 您的 PC 的默认编码.

Then it's "just" a matter of finding the right encoding. How did you create the file? If it's with Notepad then you probably want Encoding.Default - but that's obviously not portable, as it's the default encoding for your PC.

在运行良好的 Web 服务器中,响应将在其标头中指明编码.话虽如此,在某些情况下,响应标头有时会声明一件事,而 HTML 声明另一件事.

In a well-run web server, the response will indicate the encoding in its headers. Having said that, response headers sometimes claim one thing and the HTML claims another, in some cases.

这篇关于HttpWebResponse 的编码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆