HTTP Post Request - C#

HTTP Post Request - C#

code snippet

c#
private static string Post(string strURL, string strPost, string ContentType = "application/x-www-form-urlencoded", string strUserAgent = "")
        {
            string strResponseHtml = "";
            try
            {
                CookieContainer objCookieContainer = new CookieContainer();
                ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
                byte[] bytes = Encoding.UTF8.GetBytes(strPost);

                HttpWebRequest objHttpWebRequest = null;
                HttpWebResponse objHttpWebResponse = null;
                Uri objUri = new Uri(strURL);

                objHttpWebRequest = (HttpWebRequest)WebRequest.Create(objUri);
                objHttpWebRequest.Method = "POST";
                objHttpWebRequest.KeepAlive = false;
                objHttpWebRequest.ContentType = ContentType;
                objHttpWebRequest.CookieContainer = objCookieContainer;
                objHttpWebRequest.UserAgent = strUserAgent;
                objHttpWebRequest.ContentLength = bytes.Length;
                using (Stream stream = objHttpWebRequest.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();
                }

                objHttpWebResponse = (HttpWebResponse)objHttpWebRequest.GetResponse();
                strResponseHtml = new StreamReader(objHttpWebResponse.GetResponseStream()).ReadToEnd();
                objHttpWebResponse.Close();
            }
            catch (Exception ex) { strResponseHtml = ex.ToString(); }
            return strResponseHtml;
        }


private static bool ValidateRemoteCertificate(
        object sender,
            System.Security.Cryptography.X509Certificates.X509Certificate certificate,
            System.Security.Cryptography.X509Certificates.X509Chain chain,
            System.Net.Security.SslPolicyErrors policyErrors
        )
        {
            return true;
        }

"Wonder rather than doubt is the root of all knowledge"

Contact me!

Have questions? Feel free to use the form or send me an email with any questions.

I will be responsive to your requests and your questions.