|
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".
Posted by Sebastien Aube 12/20/2006 1:44:56 PM (Atlantic Standard Time, UTC-04:00)
|