有的时候需要获取某个网页的信息,有的人喜欢用webBrowser这个控件,但是这个效率并不高,我觉得System.Net.WebRequest这个效率高点,例子如下,Function:
using System.Net.Sockets;
using System.Net;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public static string GetUrltoHtml(string Url, string type) { try { System.Net.WebRequest wReq = System.Net.WebRequest.Create(Url); // Get the response instance. System.Net.WebResponse wResp = wReq.GetResponse(); System.IO.Stream respStream = wResp.GetResponseStream(); // Dim reader As StreamReader = New StreamReader(respStream) using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.GetEncoding(type))) { return reader.ReadToEnd(); } } catch (System.Exception ex) { throw ex; } return ""; } |
调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
private void btn_a_Click(object sender, EventArgs e) { string strResponse = ""; try { strResponse = GetUrltoHtml("http://xxx.com/news.asp?id=1", "utf-8"); if (!string.IsNullOrEmpty(strResponse)) this.richTextBox1.Text = strResponse; } catch(System.Exception ex) { Messagebox.show(ex.message); } } |