May 16, 2012

Making HTTPS POST using webrequest with cookie handling

A bit intro in beginning...
My credit card company is a bit lazy. In this age of IT revolution its normal to receive info and not to ask for it. In order to get my credit card account balance I need to access my online account.
This sucks.
I wanted to receive my credit card balance in email on a regular timely base. But credit card company does not allow for this. It's not like they want me to be aware of it :)

Challenge was how to do POST from windows service on HTTPS url.
Simple sniffing of POST from browser got me details for POST data.
After a bit of google-ing I came up with this.
You know that stupid feeling when you write a bit complex stuff and it works on a first try.

One must admire guys from Microsoft in doing good job.
Observe what complexity is hidden in just few lines - negotiating HTTPS protocol, handling in and out of cookies.

Cool...

Here is the code that makes actual HTTPS POST:


   var postData = "j_username=xxxxxx&j_password=xxxxxx&Submit=continue";
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] postByteArray = encoding.GetBytes(postData);

            var response = new List();
            Uri myuri = new Uri(MYURL);
   
   var cookieContainer = new CookieContainer();

   //.NET client to accept all certificates
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
        
            HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(myuri);
            webRequest.CookieContainer = cookieContainer;
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = postByteArray.Length;
            var requestStream = webRequest.GetRequestStream();
            requestStream.Write(postByteArray, 0, postByteArray.Length);
            requestStream.Close();
            
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            
            using (Stream resStream = webResponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(resStream);
                string resline = "";
                while (resline != null)
                {
                    resline = reader.ReadLine();
                    response.Add(resline);
                }
                reader.Close();
                resStream.Close();
            }
            return response.ToArray();

No comments:

Post a Comment