Request and Response in Visual Basic

Introduction: This is a simple tutorial on how to use the System.Net namespace in Visual Basic to send a request and receive a response from a server. Imports: First we need to import the namespace. This enables us to use the required functions and classes...
  1. Imports System.Net
Request: To send a request we first create an object of HTTPWebRequest...
  1. Dim req As HttpWebRequest
We then set that object equal to a new HTTPWebRequest with the function of '.Create()' while parsing it the server URL, in this case, Bing...
  1. req = HttpWebRequest.Create("http://www.bing.com")
Response: Next we create an object to hold the response. This object is the type of HTTPWebResponse...
  1. Dim res As HttpWebResponse
Next we set the response object to the request's response...
  1. res = req.GetResponse()
Done!: From now on we can use that response to do things such as get the source of the response (web page from the request server)...
  1. Using reader As New System.IO.StreamReader(res.GetResponseStream())
  2. MsgBox(reader.ReadToEnd()) 'Source
  3. End Using
Full Source: Here is the full source file...
  1. Imports System.Net
  2.  
  3. Class Form1
  4.  
  5. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  6. Dim req As HttpWebRequest
  7. req = HttpWebRequest.Create("http://www.bing.com")
  8. Dim res As HttpWebResponse
  9. res = req.GetResponse()
  10. Using reader As New System.IO.StreamReader(res.GetResponseStream())
  11. MsgBox(reader.ReadToEnd()) 'Source
  12. End Using
  13. End Sub
  14. End Class

Add new comment