-1

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#

4
  • 1
    You have a StreamReader.ReadToEndAsync - method, to use with the async/await pattern. The linked question is old, and predates the modern asynchronous patterns. Commented Feb 29, 2024 at 15:56
  • 1
    HttpWebRequest is deprecated. Get rid of all of this and use HttpClient instead. Only use Await not .Result or .Wait. Make sure you dispose with a Using. Don't mess with ServicePointManager. Commented Feb 29, 2024 at 16:03
  • @Charlieface Thank you very much for the answer, I took a look at the new documentation of HttpClient and summarized the code as follows: Using response As HttpResponseMessage = Await client.GetAsync(url) response.EnsureSuccessStatusCode() result = Await response.Content.ReadAsStringAsync() End Using The question that's bothering me now is in relation to the useragent, which I haven't yet identified how to send. Commented Feb 29, 2024 at 17:47
  • Instead of using GetAsync, you need to create a HttpRequestMessage where you can headers. then pass it to SendAsync. Commented Feb 29, 2024 at 21:03

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.