Friday, September 30, 2016

Send data by post method in C#


If you need to POST some data (XML) in a particular URL using C#, you just need to perform the next steps:

  • Create a request to the url
  • Put required request headers
  • Convert the request XML message to a stream (or bytes)
  • Write the stream of bytes (our request xml) to the request stream
  • Get the response and read the response as a string

I know it looks complicated, but once you see the code, you will clarify your ideas...
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();
        }
    }
}
Now, if the XML message is formed well, everything should be fine....



Programming Joke

Q:  Why do Java programmers have to wear glasses?
A:  Because they don't C#. (see sharp)

because, they are Visually Basic, uh?

=)



No comments:

Post a Comment