面试题答案
一键面试- 引入命名空间:
在代码文件开头引入
System.Net.Http
命名空间,这样才能使用HttpClient
类。Imports System.Net.Http
- 创建HttpClient实例:
可以在类级别定义一个
HttpClient
字段,或者在方法中创建局部实例。Private client As HttpClient = New HttpClient()
- 发送GET请求:
使用
HttpClient
的GetAsync
方法发送GET请求,该方法返回一个Task(Of HttpResponseMessage)
。
这里使用Dim responseTask As Task(Of HttpResponseMessage) = client.GetAsync("https://example.com/api/data") responseTask.Wait() Dim response As HttpResponseMessage = responseTask.Result
Wait
方法等待任务完成并获取结果,也可以使用异步编程模型(Await
)更优雅地处理,如下:Dim response As HttpResponseMessage = Await client.GetAsync("https://example.com/api/data")
- 处理响应:
如果响应成功(状态码为200 - 299),可以读取响应内容。
使用异步方式:If response.IsSuccessStatusCode Then Dim contentTask As Task(Of String) = response.Content.ReadAsStringAsync() contentTask.Wait() Dim content As String = contentTask.Result '在这里处理获取到的数据content End If
If response.IsSuccessStatusCode Then Dim content As String = Await response.Content.ReadAsStringAsync() '在这里处理获取到的数据content End If
- 处理异常:
GetAsync
方法可能会抛出异常,如网络问题等。可以使用Try - Catch
块来捕获异常。Try Dim response As HttpResponseMessage = Await client.GetAsync("https://example.com/api/data") If response.IsSuccessStatusCode Then Dim content As String = Await response.Content.ReadAsStringAsync() '在这里处理获取到的数据content End If Catch ex As Exception '处理异常,例如记录日志或向用户显示错误信息 Console.WriteLine("发生异常: " & ex.Message) End Try
注意:HttpClient
实例在应用程序生命周期内最好只创建一次,以避免资源浪费和连接问题。如果使用异步编程模型,要确保所在方法是异步的(使用Async
关键字修饰)。