天天看點

VB.NET 下載下傳網頁資料

Imports System.Net

Imports System.IO

Imports System.String   

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 

    Dim sText As string

     sText = GetPage(http://www.21cn.com, "GB2312")

    End Sub

Function GetPage(ByVal WebUrl As String, ByVal sLan As String) As String

        Try

            Dim httpReq As System.Net.HttpWebRequest      'HttpWebRequest    類對    WebRequest    中定義的屬性和方法提供支援',也對使使用者能夠直接與使用    HTTP    的伺服器互動的附加屬性和方法提供支援。    

            Dim httpResp As System.Net.HttpWebResponse      '    HttpWebResponse    類用于生成發送    HTTP    請求和接收    HTTP    響'應的    HTTP    獨立用戶端應用程式。  

            Dim url As String = WebUrl

            Dim httpURL As New System.Uri(url)

            httpReq = CType(WebRequest.Create(httpURL), HttpWebRequest)

            httpReq.Method = "GET"

            httpResp = CType(httpReq.GetResponse(), HttpWebResponse)

            Dim reader As StreamReader = _

            New StreamReader(httpResp.GetResponseStream, System.Text.Encoding.GetEncoding(sLan))    '如是中文,要設定編碼格式為“GB2312”。  

            Dim respHTML As String = reader.ReadToEnd()      'respHTML就是網頁源代碼  

            httpResp.Close()

            Return respHTML

        Catch ex As Exception

            Return "産生錯誤!"

        End Try

        Return "産生錯誤!"

    End Function