用HTTPWebrequest的CharacterSet属性时,结果总是空字符
愿意想通过HTTPWebrequest 和HttpWebResponse得到网页源代码,程序如下:
HttpWebRequest httpReq ;
HttpWebResponse httpResp ;
Uri httpUrl = new Uri("http://www.microsoft.com");
httpReq = (HttpWebRequest)WebRequest.Create(httpUrl);
httpResp = (HttpWebResponse)httpReq.GetResponse();
site.ResponseUrl = httpResp.ResponseUri.ToString();//这里赋值ResponseUrl
// httpReq.KeepAlive = false; //获取或设置一个值,该值指示是否与 Internet 资源建立持久连接
StreamReader reader = new StreamReader(httpResp.GetResponseStream(),System.Text.Encoding.Default);
sourceCode = reader.ReadToEnd(); //网页源代码
但是遇到了CharacterSet为UTF-8的网站时,得到的源代码为乱码。如果将高亮部分改为“System.Text.Encoding.UTF-8”,这些网站可以正确得到源代码,但是GB2312编码的网站又出错。察看msdn,HTTPWebrequest 的CharacterSet 属性可以返回该网站编码,可是不管哪类网站,此处值总为空字符串。(本意想通过这得到编码字符串,再调用System.Text.Encoding.GetEncoding()的)
搜索了google,类似问题没有。http://channel9.msdn.com/ShowPost.aspx?PostID=166867#166867 上看见有人报告了HttpWebResponse中get_CharacterSet()函数的bug,其实也和我想解决的无关,虽说是个bug,其实无影响。找到HttpWebResponse.cs(HttpWebResponse函数源码),http://dotnet.di.unipi.it/content/sscli/docs/doxygen/fx/bcl/httpwebresponse_8cs-source.html,也没解决问题。
----在blog上(http://blog.csdn.net/quou2002/archive/2006/03/23/633130.aspx)放放把,同时也在csdn里问问,以后再说了只能。