Click here to Skip to main content
15,888,172 members
Articles / Programming Languages / XML
Tip/Trick

Invoke a POST method with XML Request message in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
24 Apr 2014CPOL 59.8K   7   1
This tip explains how to call a web method with a POST request using xml request messaage in C#.
Hi,

To invoke a POST method located at a particular URL with an XML request message, we need to follow the below steps:

  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 above steps looks something like this:

C#
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.

Hope this helps!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionSuggested Links Pin
Member 1351790426-Nov-17 21:48
Member 1351790426-Nov-17 21:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.