as

Friday, 28 February 2014

How to send HTTP POST request to server in C#?

Below example shows how to send HTTP POST request to the web server in C#.Net

            String server= "http://www.ezybus.in";

            //create http web request.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(server);

            //if you use proxy server to connect  to the site, you will have to provide the server details and //authentication information.
            WebProxy myproxy = new WebProxy("proxy_server:8080", true);
            myproxy.Credentials = new NetworkCredential("userID", "Password");
            request.Proxy = myproxy;

            try
            {

                //3 things to send to server are - CookieContainer, PostData, ContentType

                request.Method = "POST";
             
                 String postData = "UserId=abc&UserPassword=bxnbs&enter=";
         
                 //encode post data
                 postData  = System.Web.HttpUtility.UrlEncode(postData);
             
                //here previousCookieContainer is the CookieContainer object that was used for the GET request
                request.CookieContainer = previousCookieContainer;
             
                 //convert the post data into byte array
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
             
                //set the ContentType property
                request.ContentType = "application/x-www-form-urlencoded";
             
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
               
                 //Send the POST request
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                //print the response code from the server
                Console.WriteLine(((HttpWebResponse)response).StatusDescription);

               

                dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);


               //print the response body received from the server
                string responseFromServer = reader.ReadToEnd();

                Console.WriteLine("Response of the post request is -> " + responseFromServer );

                dataStream.Close();
                response.Close();

             

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

When you send the POST request to the web server, you may get errors like session expired or Internal server error. To fix these issues, you can visit this solution.


What do you think on this topic? Please express your opinion through comment below. You can write to me at reply2sagar@gmail.com

Sponsored Links

Popular Posts

Comments

ShareThis