Send XML File From Client to Server Using REST in a Web API C# Solution

It is a common method to pass arguments to the URI to REST methods:

http://localhost:21608/api/boomerangingTelescopicPhraseMaze/gus/gus/42

What if you need to send something, though it is too long to fit within URI to an entire file? Here’s a much easier way:

        private void buttonIn_Click(object sender, EventArgs e)
        {
            String fullFilePath = @"C:\Platypi\Duckbills_JennyLind_CA.XML";
            String uri = @"http://localhost:21608/api/dplat/sendxml";
            SendXMLFile(fullFilePath, uri, 500);
        }

        public static string SendXMLFile(string xmlFilepath, string uri, int timeout)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            request.ContentType = "application/xml";
            request.Method = "POST";

            StringBuilder sb = new StringBuilder();
            using (StreamReader sr = new StreamReader(xmlFilepath))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    sb.AppendLine(line);
                }
                byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());

                if (timeout < 0)
                {
                    request.ReadWriteTimeout = timeout;
                    request.Timeout = timeout;
                }

                request.ContentLength = postBytes.Length;

                try
                {
                    Stream requestStream = request.GetRequestStream();

                    requestStream.Write(postBytes, 0, postBytes.Length);
                    requestStream.Close();

                    using (var response = (HttpWebResponse)request.GetResponse())
                    {
                        return response.ToString();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    request.Abort();
                    return string.Empty;
                }
            }
        }

Read the entire code here: http://www.codeproject.com/Tips/811436/How-to-Send-an-XML-File-From-a-Client-to-a-Server

Leave a Reply

Your email address will not be published. Required fields are marked *