WebClient类对象DownloadString属性出现乱码问题[解决方法]

使用WebClient类对象的DownloadString属性请求下载内容时,出现乱码,如:{\"content\":\"鍏呭€兼垚鍔?,\"code\":0} ,后面的斜线引号变成问号了。
原因:由于返回接受字符串的编码有问题。编码分utf-8、gb2312。
解决方法:

WebClient web = new WebClient();//创建一个webclient对象
web.Encoding = System.Text.Encoding.UTF8;//定义对象的编码语言,此处或者是gb2312
string returns = web.DownloadString("http://blog.unvs.cn");//向一个链接请求资源

还有一种获取网页资源、源代码的方法(已加注释),如下:
WebRequest hwr  =  WebRequest.Create( @" http://www.baidu.com " );//向指定Url发出请求 
HttpWebResponse hwp  =  hwr.GetResponse()  as  HttpWebResponse;//将hwr对HTTP的请求 
string  text; 
StreamReader sr; 
string  code  =  hwp.ContentType;//请求响应得到的内容类型 
// 得到编码了  
code  =  code.Split( ' = ' )[ 1 ]; Stream rep  =  hwp.GetResponseStream();//将请求得到的内容以流的形式读出 
sr  =   new  StreamReader(rep, Encoding.GetEncoding(code));//用指定的字符编码为指定的流初始化 
text  =  sr.ReadToEnd();//读取数据

 

本博文章基本上属于原创或收集整理,都是心血结晶。
欢迎转载分享,转载请注明出处,谢谢!
本文地址:http://blog.unvs.cn/archives/WebClient-DownloadString-attribute.html

转载于:https://www.cnblogs.com/Lethe/archive/2013/05/08/3066465.html

你可能感兴趣的:(WebClient类对象DownloadString属性出现乱码问题[解决方法])