vb.net使用WebClient进行http异步通讯

DownloadStringCompletedEventArgs 类
DownloadDataCompletedEventArgs 类
一个是获取字符串,一个是获取字节数组,字符串需要对属性client.Encoding = System.Text.Encoding.UTF8设置成所需要的汉字编码,否则或乱码。
获取的字节数组需要处理成汉字,用如下方法
Dim res As Byte()
res = e.Result
Dim textString As String = System.Text.Encoding.UTF8.GetString(res)
'  Sample call : DownloadStringInBackground2 ("http:' www.contoso.com/GameScores.html")
        Public Shared Sub DownloadStringInBackground2(ByVal address As String)

            Dim client As WebClient = New WebClient()

            '  Specify that the DownloadStringCallback2 method gets called
            '  when the download completes.
            AddHandler client.DownloadStringCompleted, AddressOf DownloadStringCallback2
                        Dim uri as Uri = New Uri(address)
            client.DownloadStringAsync(uri)
        End Sub

Private Shared Sub DownloadStringCallback2(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)

            '  If the request was not canceled and did not throw
            '  an exception, display the resource.
            If e.Cancelled = False AndAlso e.Error Is Nothing Then

                Dim textString As String = CStr(e.Result)
                Console.WriteLine(textString)
            End If
        End Sub

 

posted @ 2020-11-09 15:53  水星博客  阅读(1014)  评论(0)    收藏  举报