C#访问网页一般使用WebClient、WebRequest或者HttpWebRequest,如果有特殊要求另论,比如WebBrowser方式。
一、WebClient方式,代码简单,可定制性低,不能携带cookies
复制
private string GetWebClient(string url) { string strHTML = ""; WebClient myWebClient = new WebClient(); Stream myStream = myWebClient.OpenRead(url); StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("utf-8")); strHTML = sr.ReadToEnd(); myStream.Close(); return strHTML; }
二、WebRequest方式与WebClient相似,可定制性稍高
复制
private string GetWebRequest(string url) { Uri uri = new Uri(url); WebRequest myReq = WebRequest.Create(uri); WebResponse result = myReq.GetResponse(); Stream receviceStream = result.GetResponseStream(); StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8")); string strHTML = readerOfStream.ReadToEnd(); readerOfStream.Close(); receviceStream.Close(); result.Close(); return strHTML; }
三、HttpWebRequest方式开放性高,可定制各种访问参数与响应参数具体查看C#HttpWebRequest带cookies访问网页GET
四、WebBrowser浏览器对象方式访问网页,使用浏览器控件访问,不解释。
评论 (1)