首页 > 学院 > 开发设计 > 正文

c#下载网页源码的两种方法

2019-11-14 15:52:59
字体:
来源:转载
供稿:网友

1、WebClient:

System.Net.WebClient wc = new System.Net.WebClient();   Byte[] pageData = wc.DownloadData("网页地址");   string s= System.Text.Encoding.Default.GetString(pageData); //s = System.Text.Encoding.UTF8.GetString(pageData);去除中文乱码 
WebClient

2、HttPRequest:

 1 static class WebFunc    2 {    3     private static CookieContainer cookie = new CookieContainer();    4     private static string contentType = "application/x-www-form-urlencoded";    5     private static string accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-Flash, application/x-silverlight, application/vnd.ms-Excel, application/vnd.ms-Powerpoint, application/msWord, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xPSDocument, application/xaml+xml, application/x-silverlight-2-b1, */*";    6     private static string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";    7     8     /// <summary> 9     /// 10     /// </summary>11     /// <param name="url">网页地址</param>12     /// <param name="encoding">编码方式</param>13     /// <returns></returns>14     public static string GetHtmlEx(string url, Encoding encoding)   15     {   16         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);   17         request.UserAgent = userAgent;   18         request.ContentType = contentType;   19         request.CookieContainer = cookie;   20         request.Accept = accept;   21         request.Method = "get";   22   23         WebResponse response = request.GetResponse();   24         Stream responseStream = response.GetResponseStream();   25         StreamReader reader = new StreamReader(responseStream, encoding);   26         String html = reader.ReadToEnd();   27         response.Close();   28   29         return html;   30     }   31 }  
HttpRequest

转自http://blog.csdn.net/adsdassadfasdfasdf/article/details/5831347


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表