VB.Net 8 根据URL获取网页HTML
Public Shared Async Function GetHTML(URL As String) As Task(Of String)
Using client As New HttpClient()
Try
'设置超时限制,有效防止浪费资源
client.Timeout = TimeSpan.FromSeconds(30)
'使用 GetAsync 进行异步 HTTPGET 请求
Dim response As HttpResponseMessage = Await client.GetAsync(URL)
'确认响应成功,否则抛出异常
response.EnsureSuccessStatusCode()
'异步读取响应为字符串
Dim responseBody As String = Await response.Content.ReadAsStringAsync()
Return responseBody
Console.WriteLine(responseBody)
Catch e As HttpRequestException
Return ""
Console.WriteLine("Error Message :{0} ", e.Message)
End Try
End Using
End Function
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim T As Task(Of String) = GetHTML("http://www.tiancao.net")
Dim result As String = Await T
Me.TextBox1.Text = result
End Sub