Wednesday, February 27, 2019

Post Request With XML Data To Web Server Using C#

This is how we post a request with XML Data to Web Server

public string PostServerRequest(string dataXML)
        {
            // Prepare web request to POST to server.
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(dataXML);
            HttpWebRequest myRequest =  (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["ServerURL"]);
            myRequest.Method = "POST";
            myRequest.ContentType = "text/xml";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            // Send the data to server
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            WebResponse response = myRequest.GetResponse();
            var status = ((HttpWebResponse)response).StatusDescription;

            // Get the stream containing content returned by the server 
            newStream = response.GetResponseStream();// Open the stream using a StreamReader for easy access  
            StreamReader reader = new StreamReader(newStream);
            // Return the content  
            return reader.ReadToEnd();
        }

No comments:

Post a Comment