While doing modeling for the new project that requires a HTTPS communication by posting some xml messages, I've encountered a few intricacies in the Compact Framework. First problem I’ve hit when trying to use the code that’s been working fine for me in the previous project to send a POST request over SSL is the known bug that throws a Socket exception. To workaround it I had to stop using ContentLength of the request class and set the AlllowWriteStreamBuffering to true. Another problem I ran into is that I was getting a TrustFailure exceptions due to a security certificate on the web server I was accessing is not fully trusted. A quick search on the Google brought up a great post by Jan Tielens that suggested implementing the ICertificatePolicy interface. It worked like a charm. The last problem came into play when I discovered that the web site requires passing a session cookies after logging in. That was easily resolved by getting the cookies from the WebResponse.Headers collection and setting it back in the request object. Here’s the snippet of the final working code:
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType="application/x-www-form-urlencoded";
//request.ContentLength = parameters.Length;
request.AllowWriteStreamBuffering = true; //required for bug workaround
request.Timeout = 60000;
if (sessionCookies!="")
{
string[] cookies = sessionCookies.Split(';');
// We've got some cookies
if (cookies.Length > 0)
{
request.Headers.Add("Cookie", cookies[0]);
}
else
{
request.Headers.Add("Cookie", sessionCookies);
}
}
//Get request stream
Stream requestStream = request.GetRequestStream();
//Write a post values
requestStream.Write(Encoding.ASCII.GetBytes(parameters), 0, parameters.Length);
requestStream.Close();
// Get response
response = (HttpWebResponse)request.GetResponse();
if (sessionCookies == "")
{
//Get the cookies
sessionCookies = response.Headers["Set-Cookie"];
}
reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
response.Close();