Derek Hatchard blogs on
Church Radius Blog


Feed Yourself:


Subscribe in Bloglines

Add to Google

Subscribe by Email:


.NET Experts on Tap
About ArdentDev.com
Ardent Sites
Ask the Experts
Careers
Consulting and Mentoring
Contact Ardent
News & Noteworthy
Portfolio
Writing


On this page....
POSTing to a webpage and using it's response (HttpWebRequest and HttpWebResponse)

Send mail to the authors Email Us

Archives

Navigation

Categories
 Code
 Tools

Disclaimer
The opinions expressed in this site are those of the individual authors and do not necessarily represent the official view of Ardent Development nor its employees, subsidiaries, partners, or customers.

© Copyright 2008, Ardent Development

Powered by: newtelligence dasBlog 1.8.5223.1



 Wednesday, December 20, 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
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)
#   Disclaimer  |  Comments [0]  | 
 
© 2005 Ardent Development Solutions