Invoking a POST Method Located at a Specific URL With XML Request

Introduction

Use the following procedure to invoke a POST method located at a specific URL with an XML request message:

1. Create a request to the URL
2. Put required request headers
3. Convert the request XML message to a stream (or bytes)
4. Write the stream of bytes (our request XML) to the request stream
5. Get the response and read the response as a string

This looks much easier when seen in code. Keep reading.
So, the code for the preceding procedure looks something like this:

namespace HttpPostRequestDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            string xmlMessage = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n" +

            "construct your xml request message as required by that method along with parameters";

            string url = "http://XXXX.YYYY/ZZZZ/ABCD.aspx";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

 

 

            byte[] requestInFormOfBytes = System.Text.Encoding.ASCII.GetBytes(xmlMessage);

            request.Method = "POST";

            request.ContentType = "text/xml;charset=utf-8";

            request.ContentLength = requestInFormOfBytes.Length;

            Stream requestStream = request.GetRequestStream();

            requestStream.Write(requestBytes, 0, requestInFormOfBytes.Length);

            requestStream.Close();

 

 

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader respStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);

            string receivedResponse = respStream.ReadToEnd();

 

            Console.WriteLine(receivedResponse);

            respStream.Close();

            response.Close();

        }

    }

}

If the xmlMessage is formed correctly, then you should be getting the expected response from the web method located at the URL.

I hope this helps!


Similar Articles