View Sidebar
POSTing to a webpage and using it’s response (HttpWebRequest and HttpWebResponse)

POSTing to a webpage and using it’s response (HttpWebRequest and HttpWebResponse)

December 20, 2006 5:44 pm2 comments
You might encounter a situation where you need to Post to a web page and read it’s
response.

Here’s a function that uses System.Net.HttpWebRequest and System.Net.HttpWebResponse
to do just that.

      ' Usage:
      '   Dim xmlDoc As Xml.XmlDocument
      '   xmlDoc.Load(MakeHttpRequest( _
                           "request=listPersons&filter=last(a*)", _
                           "/requestManager.php", _
                           "application/x-www-form-urlencoded")) 

      Protected Function MakeHttpRequest(
                                   ByVal data As String, _
                                   ByVal url As String, _
                                   ByVal contentType As String) _
                                   As System.IO.Stream
        Dim retVal As System.IO.Stream 
        Dim httpRequest As System.Net.HttpWebRequest 
        Dim httpResponse As System.Net.HttpWebResponse 
        Dim encoding As New System.Text.UTF8Encoding
        Dim uri As New System.Uri(url) 
        Dim postBytes As Byte() postBytes = encoding.GetBytes(data)      
        httpRequest = CType(System.Net.HttpWebRequest.Create(uri), _
                                     System.Net.HttpWebRequest)      
        httpRequest.ContentLength = postBytes.Length 
        httpRequest.Method = "POST" 
        httpRequest.ContentType      = contentType 
        Dim postStream As System.IO.Stream = _
                                 httpRequest.GetRequestStream()      
        postStream.Write(postBytes, 0, postBytes.Length) 
        postStream.Close() 
        httpResponse = CType(httpRequest.GetResponse(), System.Net.HttpWebResponse) 
        retVal = httpResponse.GetResponseStream()
        Return retVal
      End Function
      

Variation: If the webpage you are calling expects xml you could easily replace and
pass a valid xml string as data
replace
httpRequest.ContentType = "application/x-www-form-urlencoded"

with
httpRequest.ContentType = "text/xml"

You could even go further and return an xml document if the expected datatype is
“text/xml”.