Blog

HTTP GET/POST using VB.NET and BackgroundWorker Class

August 9, 2012

A simple code example using VB.NET LAMDA’s to create an inline BackgroundWorker object. I’m not a VB guru so there may be better ways to do this.
MY REQUIREMENTS:

  1. Inline (all started from a single CLICK event)
  2. Async HTTPWebRequest
  3. Populate ComboBox/Input with JSON formatted request results
  4. VB.NET
Dim requestWorker As BackgroundWorker = New BackgroundWorker()

AddHandler requestWorker.DoWork, Sub(workerSender As Object, workerEvent As System.ComponentModel.DoWorkEventArgs)

Dim request As HttpWebRequest = CType(WebRequest.Create("http://www.contoso.com/somepage.html"), HttpWebRequest)

request.Method = "POST" ' Also "GET" allowed

' For POST operations request, not required for GET

Dim data As String = "var1=1&var2=2&var3=test"

request.ContentType = "application/x-www-form-urlencoded"

request.ContentLength = System.Text.Encoding.ASCII.GetBytes(data).Length

Dim requestStreamWriter As StreamWriter = New StreamWriter(request.GetRequestStream())

requestStreamWriter.Write(data)

requestStreamWriter.Flush()

requestStreamWriter.Close()

' End POST operation requirements

Dim response As String = New StreamReader(resourcesRequest.GetResponse().GetResponseStream(), System.Text.Encoding.UTF8).ReadToEnd()

Dim results As Dictionary(Of String, Object) = New Script.Serialization.JavaScriptSerializer().Deserialize(Of Dictionary(Of String, Object))(response)

' Do something with the results 
If results.ContainsKey("Response") Then

' Allows cross thread input manipulation
Me.Invoke(Sub(Items As Dictionary(Of String, Object))

Me.cmbMyList.Items.Clear()

For Each Item In results.Item("Response")

Me.cmbResource.Items.Add(Item.value)

Next

End Sub, results)

End If

End Sub

requestWorker.RunWorkerAsync()

0 Comments

Leave Your Comment

Your email address will not be published.


about me

An information technology professional with twenty three years experience in systems administration, computer programming, requirements gathering, customer service, and technical support.