HttpWebRequest到HttpClient后发帖请求

时间:2018-03-31 12:35:08

标签: c# vb.net httpclient

使用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:我

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

有什么建议吗?

同样在c#

1 个答案:

答案 0 :(得分:2)

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

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

避免异步Subs / void。在这种情况下,需要返回Task的函数来正确等待异步函数。