Friday, April 5, 2013

Send XML data through web service as POST (Attachment)

By this piece of code in C# we can send the data to the web service as an attachment in the POST method.


                ASCIIEncoding encoding = new ASCIIEncoding();
                string postdata = "<Root><Info>Value</Info></Root>";
                byte[] data = encoding.GetBytes(postdata);
                Uri uri = new Uri("Your service url");
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(uri);
                myRequest.Method = "POST";
                myRequest.ContentType = "text/xml;charset=utf-8";
                myRequest.Timeout = 30000;
                NetworkCredential netCredentials = new NetworkCredential("Username", "Password");
                CredentialCache crendentials = new CredentialCache();
                crendentials.Add(uri, "Basic", netCredentials);
                myRequest.Credentials = crendentials;
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
           
// Send the data.
                newStream.Write(data, 0, data.Length);
                newStream.Close();

                // Get response

                using (HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream
                    System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                    Stream objStream = response.GetResponseStream();
                    StreamReader objSR = new StreamReader(objStream, encode, true);
                    string sResponse = objSR.ReadToEnd();
                }

Motivational qoutes

पूरे विश्वास के साथ अपने सपनों की तरफ बढ़ें। वही ज़िन्दगी जियें जिसकी कल्पना आपने की है।