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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM