Post XML Data to an Asp or Php page using C#

In one of my recent project, i had requirement to post XML file to one of the third party site on need basis. The third party site was not supporting soap web service or restful service to upload files from our site.Instead third party site had webpage to accept XML files via Http post request.

Posting XML file to an Asp or Php Server page
In this article,I wanted to share how i developed simple method using inbuilt .net framework API to accomplish this task

The method is below.

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

 public class HttpRequestHelper

    {
        public static bool UploadFile(byte[] fileBytes, string mimeType, string url)
        {

            Uri uri = new Uri(url);

            string boundary = String.Format("----------{0:x}", DateTime.Now.Ticks);
            const string errorTag = "title";
            HttpWebRequest webrequest = null;
            HttpWebResponse webresponse = null;
            Stream requestStream = null;
            StreamReader responseReader = null;
     
            try
            {
              //Create http request
                webrequest = (HttpWebRequest)WebRequest.Create(uri);
                webrequest.ContentType = String.Format("multipart/form-data; boundary={0}", boundary);
                webrequest.Method = "POST";

               //set request header

                byte[] postHeaderBytes = GetFileUploadRequestHeader(mimeType, boundary);

               //set boundry bytes. this is a must for successful upload of file

                byte[] boundaryBytes = Encoding.ASCII.GetBytes(String.Format("\r\n--{0}\r\n", boundary));
                webrequest.ContentLength = postHeaderBytes.Length + fileBytes.Length + boundaryBytes.Length;

                requestStream = webrequest.GetRequestStream();


                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

                requestStream.Write(fileBytes, 0, fileBytes.Length);
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                webresponse = (HttpWebResponse)webrequest.GetResponse();


                if (webresponse != null)

                {
                    if (webresponse.StatusCode == HttpStatusCode.OK)
                    {
                       //get the response text. 
                        responseReader = new StreamReader(webresponse.GetResponseStream());
                        string response =responseReader.ReadToEnd();
                        Console.WriteLine(response)
                        return true.
                    }
                    else
                        Console.WriteLine(webresponse.StatusDescription);
                }
                else
                    Console.WriteLine("Failed to get response from requested URL");
            }
            catch (WebException ex)
            {
                using (var reader = new StreamReader(ex.Response.GetResponseStream()))
                {
                    string response = reader.ReadToEnd();
                    Console.WriteLine(response);
                }
            }
            finally
            {

            //close all connections

                webrequest = null;

                if (webresponse != null)

                {
                    webresponse.Close();
                    webresponse = null;
                }
                if (requestStream != null)
                {
                    requestStream.Close();
                    requestStream = null;
                }
                if (responseReader != null)
                {
                    responseReader.Close();
                    responseReader = null;
                }
            }
            Console.WriteLine(error);
            return false;
        }

        #region private methods

        private static byte[] GetFileUploadRequestHeader(string mimeType, string boundary)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(boundary);
            sb.Append(Environment.NewLine);
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append("file");
            sb.Append("\"; filename=\"");
            sb.Append("\"");
            sb.Append(Environment.NewLine);
            sb.Append("Content-Type: ");
            sb.Append(mimeType);
            sb.Append(Environment.NewLine);
            sb.Append(Environment.NewLine);
            return Encoding.UTF8.GetBytes(sb.ToString());
        }
        #endregion
    }


No comments: