vb.net 教程 12-8 WebRequest 和 Webresponse 2 获得网页资源

通常的操作步骤:
1、通过WebRequest.Create(网页地址)得到WebRequest
2、通过WebRequest.GetResponse得到WebResponse
3、通过Webresponse.GetResponseStream得到返回的数据流
4、对流进行操作
5、关闭流
具体代码如下:
 

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim addr As String = TextBox2.Text

        Try
            Dim myWebRequest As WebRequest = WebRequest.Create(addr)
            Dim myWebresponse As WebResponse = myWebRequest.GetResponse

            Dim mystream As Stream = myWebresponse.GetResponseStream

            Dim singleReadCount As Integer = 10240
            Dim mybyte(singleReadCount - 1) As Byte
            Dim strpagecontent As String = ""

            Dim intreadl As Integer = 0
            Dim readcount As Integer = 0
            Do
                intreadl = mystream.Read(mybyte, 0, singleReadCount)
                readcount += 1
                'strpagecontent &= Encoding.GetEncoding("gb2312").GetString(mybyte, 0, intreadl)
                strpagecontent &= Encoding.UTF8.GetString(mybyte, 0, intreadl)
            Loop While intreadl > 0

            TextBox1.Text = strpagecontent
            Console.WriteLine(readcount)
            mystream.Close()
            myWebresponse.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub

注意:对流操作时,需要按照网页使用的编码将字节数组还原为字符串,错误的编码导致获得的文本乱码。
运行如下:
vb.net 教程 12-8 WebRequest 和 Webresponse 2 获得网页资源

由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。

学习更多vb.net知识,请参看vb.net 教程 目录

上一篇:Python9-进程-day36


下一篇:Mybatis - 值传递的4种方式