I would like to know how I can change the function below to the async method
my code:
Public Function GetPostWebService(urlget As String, stringdata As String) As String
Dim result As String = ""
Dim url As String
If internet_on_line = True Then
Try
Dim milliseconds = CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1)).TotalMilliseconds)
Dim uncache = milliseconds.ToString
url = "https://" & apiUrl & "/webservice/" & urlget & "&data=" & stringdata & "&uncache=" & uncache
Console.WriteLine("URL: " & url)
Dim fr As System.Net.HttpWebRequest
Dim targetURI As New Uri(url)
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
fr = DirectCast(WebRequest.Create(targetURI), System.Net.HttpWebRequest)
fr.UserAgent = "Mozilla/4.0 (compatible)"
fr.Timeout = 15000
Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())
result = str.ReadToEnd()
str.Dispose()
str.Close()
Return result
Catch ex As Exception
result = "[ERROR]"
Return result
Dim func_name = New StackTrace(ex).GetFrame(0).GetMethod().Name
If func_name = "GetResponse" Then
writeExeption(ex, False)
Else
writeExeption(ex, True)
End If
Console.WriteLine("GetPostWebService Falhou: " & ex.Message & " - " & result)
End Try
Else
result = "[ERROR]"
Return result
End If
End Function
I tried to use the suggestion given in this link: Implementing HttpWebRequest Async calls, but I was unable to implement it.
Any suggestions on how I can transform this function into asynchronous mode? The examples can be in both VB.net and C#
StreamReader.ReadToEndAsync- method, to use with the async/await pattern. The linked question is old, and predates the modern asynchronous patterns.HttpWebRequestis deprecated. Get rid of all of this and useHttpClientinstead. Only useAwaitnot.Resultor.Wait. Make sure you dispose with aUsing. Don't mess withServicePointManager.Using response As HttpResponseMessage = Await client.GetAsync(url) response.EnsureSuccessStatusCode() result = Await response.Content.ReadAsStringAsync() End UsingThe question that's bothering me now is in relation to the useragent, which I haven't yet identified how to send.GetAsync, you need to create aHttpRequestMessagewhere you can headers. then pass it toSendAsync.