Search code examples
c#vb.nethttpclienthttpwebrequesthttpwebresponse

Transform synchronous function into asynchronous


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#


Solution

  • With the help of @Charlieface and also from @JonasH, I managed to put together the code below and it is working perfectly.

    Public Function GetPostWebService(urlget As String, stringdata As String) As String
     Dim url As String
     Dim result As String = ""
     Try
     Dim milliseconds = CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1)).TotalMilliseconds)
     Dim uncache = milliseconds.ToString
    
     url = "https://" & apiUrl & "/webservice/" & urlget & "?token=" & data.app_config_token & "&data=" & stringdata & "&uncache=" & uncache
    
     Using client As HttpClient = New HttpClient()
         client.DefaultRequestHeaders.Clear()
         client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")
         Using response As HttpResponseMessage = Await client.GetAsync(url)
             response.EnsureSuccessStatusCode()
             result = Await response.Content.ReadAsStringAsync()
             Console.WriteLine(result)
             Return result
         End Using
     End Using
    
    Catch ex As HttpRequestException
     Console.WriteLine(vbLf & "Exception Caught!")
     Console.WriteLine("Message :{0} ", ex.Message)
     result = "[ERROR]"
     Return result
     writeExeption(ex, True)
    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
    End Function