with HttpWebRequest i use this code to post request and wait to get an async response
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
I tried to 'translate' the code to HttpClient in this mode
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
But i need to understand how to approach to HttpClient.
While in the HttpWebRequest: i
With HttpClient: i
Any suggestion?
Also in c#
Net.Http.HttpClient
has a primarily task based API. As for hooking a response to a request, No need. Just await the resposne and use it as desired once returned.
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
Avoid async Subs/void. In this case a function returning a Task
would be required to properly await the async functions.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments