How to create a POST request and send XML data

Hi,

Many a times when we are working with the third party services we have to pass the data to the third party over the web. Most of the times we pass the data in the querystring. The data is passed in a get request along with the querystring. The third party takes the value from the querystring and process the data.

But many a times the data need to be passed in the Post method. Many a third party component takes the data in XML format in the POST request. In these cases we have to pass the data as XML string in the post request. Here is an example on how to pass XML in the post request.

string xml = “SomeXML Data”;

string url = @”http://www.vikramlakhotia.com/HomePage.aspx”;

WebRequest request = WebRequest.Create(url);

request.Method = "Post";

request.ContentType = "text/xml";

//The encoding might have to be chaged based on requirement

UTF8Encoding encoder = new UTF8Encoding();

byte[] data = encoder.GetBytes(xml); //postbody is plain string of xml

request.ContentLength = data.Length;

Stream reqStream = request.GetRequestStream();

reqStream.Write(data, 0, data.Length);

reqStream.Close();

System.Net.WebResponse response = request.GetResponse();

System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());

string str = reader.ReadToEnd();

That’s all you need to do to send XML in a post request.

Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 12/26/2007 11:21:47 PM

Nice information. But I think it is not always required that we post the data as XML, we can post normal data as well.

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2009 Vikram Lakhotia