Bookmark and Share BitCoin Donate: 13t8gAWVpHP2ddxMp88d1NFpZjnFJC6UwK

Post data to a webpage c# example code

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

namespace ashrdotnet{
    public class WebPost{
	static CookieContainer cookieContainer = new CookieContainer();
        private static string postData(Dictionary data, string URL)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
				request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";
				request.CookieContainer = cookieContainer;
				request.AllowAutoRedirect = true;
				

                StringBuilder postData = new StringBuilder();
                foreach (KeyValuePair kv in data)
                {
                    if(postData.Length == 0)
                        postData.Append(kv.Key + "=" + kv.Value);
                    else
                        postData.Append("&" + kv.Key + "=" + kv.Value);
                }

                byte byteArray = Encoding.UTF8.GetBytes (postData.ToString());
                request.ContentLength = byteArray.Length;

                Stream dataStream = request.GetRequestStream ();
                dataStream.Write (byteArray, 0, byteArray.Length);
                dataStream.Close ();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    using (StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream()))
                    {
                        string returnData = streamReader.ReadToEnd();
                        return returnData;
                    }
                }
                else
                {
                    Console.WriteLine("Request for " + request.RequestUri.ToString() + " failed with " + response.StatusCode.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return null;
        }
    }
}