In the code below, DoGet is working very stable. But DoPost throws an uncatcheable InvalidOperationException randomly. I am lost. Any pointers will be of immense help.
/*
Environment
-------------
* NET CF 2.0
* WM 5.0(USA Mobile Pocket PC Emulator)
* Windows XP Professional SP2
* VS 2008
*/
/*
The exception
------------------
at System.Net.HttpWebRequest.set_ContentLength(Int64 value)
at System.Net.HttpWebRequest.BufferConnectStream.WritingSucceeds()
at System.Net.HttpWriteStream.doClose()
at System.Net.HttpWriteStream.Finalize()
*/
public static string DoPost(string url)
{
// initialize from variables
string responseString = string.Empty;
ASCIIEncoding encoding = new ASCIIEncoding();
HttpWebResponse response;
byte[] data = encoding.GetBytes("dummy");
StreamReader reader;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
//do the processing
SetRequestProperties(request, "POST"); // SETTING METHOD TO POST HERE
request.GetRequestStream().Write(data, 0, data.Length);
request.GetRequestStream().Close();
response = (HttpWebResponse)request.GetResponse();
reader = new StreamReader(response.GetResponseStream());
responseString = reader.ReadToEnd();
//clean up
response.Close();
response.GetResponseStream().Close();
response.GetResponseStream().Dispose();
reader.Close();
reader.Dispose();
reader = null;
response = null;
request = null;
encoding = null;
//return
MessageBox.Show("POST SUCCESS");
return responseString;
}
public static string DoGet(string url)
{
// initialize from variables
string responseString = string.Empty;
ASCIIEncoding encoding = new ASCIIEncoding();
HttpWebResponse response;
byte[] data = encoding.GetBytes("dummy");
StreamReader reader;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
//do the processing
SetRequestProperties(request, "GET"); // SETTING METHOD TO GET HERE
response = (HttpWebResponse)request.GetResponse();
reader = new StreamReader(response.GetResponseStream());
responseString = reader.ReadToEnd();
//clean up
response.Close();
response.GetResponseStream().Close();
response.GetResponseStream().Dispose();
reader.Close();
reader.Dispose();
reader = null;
response = null;
request = null;
encoding = null;
//return
MessageBox.Show("GET SUCCESS");
return responseString;
}
private static void SetRequestProperties(HttpWebRequest request, string s)
{
request.Method = s;
request.AllowWriteStreamBuffering = true;
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
request.SendChunked = false;
request.Credentials = CredentialCache.DefaultCredentials;
request.UserAgent = "my mobile user agent";
request.Timeout = 60000;
request.ProtocolVersion = new System.Version("1.1");
}