HttpWebRequest example with error handling (VB.Net)

This VB.Net example explains how to GET or POST a request to a web server using the .NET framework classes HttpWebRequest and HttpWebResponse. A C# version is also available.

The WRequest() parameters are: URL, HTTP_method, POST_data
  • URL: Any valid URL.
  • HTTP_method: Use "GET" to make a normal request or "POST" to submit additional (form) data along with the request.
  • POST_data: An empty string if HTTP_method "GET" is used, a string of POST data if HTTP_method "POST" is used. The format is "param1=value1&param2=value2"
Function WRequest(URL As String, method As String, POSTdata As String) As String
  Dim responseData As String = ""
    Dim cookieJar As New Net.CookieContainer()
    Dim hwrequest As Net.HttpWebRequest = Net.Webrequest.Create(URL)
    hwrequest.CookieContainer = cookieJar
    hwrequest.Accept = "*/*"
    hwrequest.AllowAutoRedirect = true
    hwrequest.UserAgent = "http_requester/0.1"
    hwrequest.Timeout = 60000
    hwrequest.Method = method
    If hwrequest.Method = "POST" Then
      hwrequest.ContentType = "application/x-www-form-urlencoded"
      Dim encoding As New Text.ASCIIEncoding() 'Use UTF8Encoding for XML requests
      Dim postByteArray() As Byte = encoding.GetBytes(POSTdata)
      hwrequest.ContentLength = postByteArray.Length
      Dim postStream As IO.Stream = hwrequest.GetRequestStream()
      postStream.Write(postByteArray, 0, postByteArray.Length)
    End If
    Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
    If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
      Dim responseStream As IO.StreamReader = _
        New IO.StreamReader(hwresponse.GetResponseStream())
      responseData = responseStream.ReadToEnd()
    End If
    Catch e As Exception
      responseData = "An error occurred: " & e.Message
    End Try
  Return responseData
End Function


wData = WRequest("http://server/", "GET", "")

wData = WRequest("http://server/rd.aspx", "POST", "name=jane&stat=active")

Page last updated 2011-10-10 19:25. Some rights reserved (CC by 3.0)



RSS 2.0 feed All content
RSS 2.0 feed ajax
RSS 2.0 feed asp
RSS 2.0 feed aspnet
RSS 2.0 feed bicycle
RSS 2.0 feed copenhagen
RSS 2.0 feed databases
RSS 2.0 feed denmark
RSS 2.0 feed diy
RSS 2.0 feed dotnet
RSS 2.0 feed html
RSS 2.0 feed japan
RSS 2.0 feed javascript
RSS 2.0 feed modding
RSS 2.0 feed photography
RSS 2.0 feed utilities
RSS 2.0 feed vbscript