Tuesday, March 4, 2014

How to send HTTPS Post Request with C#

  • Create new C# website application.
  • Open the default code behind file i.e. Default.aspx.cs
  • add the following two namespace
    using System.Security.Cryptography.X509Certificates;
    using System.Net;
For the https request we have to create a CertificatePolicy  subclass which is

public class MyPolicy : ICertificatePolicy
{
    public bool CheckValidationResult(ServicePoint srvPoint,
      X509Certificate certificate, WebRequest request,
      int certificateProblem)
    {
        //Return True to force the certificate to be accepted.
        return true;
    }
}

Now go to the page load event and paste the following code.
protected void Page_Load(object sender, EventArgs e)
{
        System.Net.ServicePointManager.CertificatePolicy = new MyPolicy(); 
       // this is CertificatePolicy  subclass
        try
        {
            string url = "https://myirl.com";
            HttpWebRequest req=(HttpWebRequest)WebRequest.Create(url);
            req.KeepAlive = false;
            req.AllowAutoRedirect = true;
            req.ProtocolVersion = HttpVersion.Version10;
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] postBytes = Encoding.ASCII.GetBytes("username=sample_post_data");
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = postBytes.Length;
            Stream requestStream = req.GetRequestStream();
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();            

            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            Stream resStream = response.GetResponseStream();

            var sr = new StreamReader(response.GetResponseStream());
            string responseText = sr.ReadToEnd();
            Response.Write(responseText);
        }
        catch (Exception ee)
        {
        }
    }
}

If you want to convert the response test to xml, then add the xml namespace as using System.Xml; then add the following code below the responseText as
XmlDocument doc = new XmlDocument();
doc.LoadXml(responseText);
Now you can use this xml result according to your requirement.

1 comment: