HttpWebRequest to HttpClient post Request



使用 HttpWebRequest,我使用此代码发布请求并等待获得异步响应

Private Async Sub SendHttpWebReq(ByVal jsonString as String)
' create the HttpWebRequest
Dim httpWebReq = CType(Net.WebRequest.Create("http://www.foo.foo"), Net.HttpWebRequest)
' set the HttpWebRequest
httpWebReq.Method = "POST"
httpWebReq.KeepAlive = True
httpWebReq.ContentType = "application/json"
With httpWebReq.Headers
.Add(Net.HttpRequestHeader.AcceptCharSet, "ISO-8859-1,utf-8")
.Add("X-User", user)
End With
' transform the json String in array of Byte
Dim byteArray as Byte() = Encoding.UTF8.GetBytes(jsonString)
' set the HttpWebRequest Content length
httWebReq.ContentLEngth = byteArray.Length
' create a HttpWebRequest stream
Dim dataStream as IO.Stream = httpWebReq.GetRequestStream()
' send the request in a stream
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
' create the HttpWebRequest response
Dim Response as Net.WebResponse = Await httpWebReq.GetResponseAsync()
Dim ResponseStream as IO.Stream = Response.GetResponseStream()
End Sub

我试图将代码"翻译"为HttpClient。 在此模式下

Dim HttpClientReq as HttpClient
With HttpClientReq
.BaseAddress = New Uri("Http://www.foo.foo")
.DefaultRequestHeaders.Accept.Clear()
.DefaultRequestHeaders.Accept.Add(New Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")
.DefaultRequestHeaders.Add("X-User", user)
End With
Private Async Sub SendHttpClientReq(Byval jsonString as String)
Dim Request As Net.Http.HttpRequestMessage
Request.Content = New Net.Http.StringContent(jsonString, System.Text.Encoding.UTF8, "application/json")
Dim Response as Net.Http.HttpResponseMessage = Await HttpClientReq.PostAsync(HttpClientReq.BaseAddress)
End sub

但是我需要了解如何使用HttpClient。

在 HttpWebRequest 中:i

  • 创建类的实例
  • 设置参数(和标头)
  • 发布请求
  • 创建等待服务器响应的响应
  • 将响应挂接到请求,我收到服务器响应

使用 HttpClient: i

  • 创建类的实例
  • 设置参数(和标头)
  • 发布请求
  • 我没有看到任何让我将响应挂钩到请求的方法,所以我不知道如何等待收到响应。

有什么建议吗?

同样在 C# 中

Net.Http.HttpClient有一个主要基于任务的API。至于挂钩对请求的响应,没有必要。只需等待回复,并在返回后根据需要使用它。

Dim client As HttpClient
With client
.BaseAddress = New Uri("Http://www.foo.foo")
.DefaultRequestHeaders.Accept.Clear()
.DefaultRequestHeaders.Accept.Add(New Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")
.DefaultRequestHeaders.Add("X-User", user)
End With
'...'
Private Async Function PostAsync(Byval jsonString as String) As Task
Dim content As New Net.Http.StringContent(jsonString, System.Text.Encoding.UTF8, "application/json")
Dim response As Net.Http.HttpResponseMessage = Await client.PostAsync("", content)
Dim result As String = Await response.Content.ReadAsStringAsync()
'do something with the result.'
End Function

避免异步订阅/无效。在这种情况下,需要返回Task的函数才能正确等待异步函数。

最新更新