POSTing to a webpage and using it’s response (HttpWebRequest and HttpWebResponse)
Posted by derek Code December 20th, 2006 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
with
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”.
Read a great book: Good to Great: Why Some Companies Make the Leap… and Others Don’t
by Jim Collins


Recent Comments