Home > Software engineering >  How to execute a webrequest asynchronous to parse json
How to execute a webrequest asynchronous to parse json

Time:01-04

I need to get a value from an API and I'm using the follow code synchronous.

       Dim request As HttpWebRequest
       Dim response As HttpWebResponse = Nothing
       Dim reader As StreamReader

       Try

           request = DirectCast(WebRequest.Create("http://ecc"), HttpWebRequest)

           response = DirectCast(request.GetResponse(), HttpWebResponse)
           reader = New StreamReader(response.GetResponseStream())

           Dim rawresp As String
           rawresp = reader.ReadToEnd()

           Dim jResults As JObject = JObject.Parse(rawresp)
           Label1.Text = jResults("result").ToString()


       Catch ex As Exception
           MsgBox(ex.ToString)
       Finally
           If Not response Is Nothing Then response.Close()

       End Try

The problem is that's synchronous, I want to make it async in order not to freeze the form in the while. How can I async it?

CodePudding user response:

You can easily use WebClient and the nuget package NewtonSoft doing something like this:

Imports System.IO
Imports System.Net
Imports System.Text
Imports Newtonsoft.Json

Public Class Form1
    Private ReadOnly wc As New WebClient()

 Private Async Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

        'stop timer to avoid simultaneous I/O operations
        Timer1.Stop()

        Dim downloadTasks As New List(Of Task(Of String))

        'download api and add as a task of string
        Dim APIValue = wc.DownloadStringTaskAsync("https://api.etc")
        downloadTasks.Add(Value)
        Await Task.WhenAll(downloadTasks)
        Dim d = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(APIValue.Result)

        Dim Price As String = d("result").ToString
        Label1.Text = Price

        Timer1.Start()
 End Sub
 End Class

CodePudding user response:

Much simpler with HttpClient and JsonNode:

'// Web API:
'// app.MapGet("/api", () => new { id = 1, result = "100", name = "name1" });

Using http = New HttpClient
  Dim url = "https://localhost:5000/api"
  Dim json = JsonNode.Parse(Await http.GetStreamAsync(url))
  Label1.Text = json("result")
End Using
  •  Tags:  
  • Related