Asynchronous WebRequest with POST-parameters in .NET Compact Framework

Tommi Forsström picture Tommi Forsström · Apr 20, 2009 · Viewed 9.4k times · Source

I'm trying to do an asynchronous HTTP(S) POST on .NET Compact Framework and I can't seem to get it working.

Here's what I'm doing:

private void sendRequest(string url, string method, string postdata) {
    WebRequest rqst = HttpWebRequest.Create(url);
    CredentialCache creds = new CredentialCache();
    creds.Add(new Uri(url), "Basic", new NetworkCredential(this.Uname, this.Pwd));
    rqst.Credentials = creds;
    rqst.Method = method;
    if (!String.IsNullOrEmpty(postdata)) {
        rqst.ContentType = "application/xml";
        byte[] byteData = UTF8Encoding.UTF8.GetBytes(postdata);
        rqst.ContentLength = byteData.Length;
        using (Stream postStream = rqst.GetRequestStream()) {
            postStream.Write(byteData, 0, byteData.Length);
            postStream.Close();
        }
    }
    ((HttpWebRequest)rqst).KeepAlive = false;
    rqst.BeginGetResponse(DataLoadedCB, rqst);
}

private void DataLoadedCB(IAsyncResult result) {
    WebRequest rqst = ((WebRequest)(((BCRqst)result.AsyncState).rqst));
    WebResponse rsps = rqst.EndGetResponse(result);

    /* ETC...*/
}

...but for some reason I get a WebException on the second row of DataLoadedCB:

"This request requires buffering of data for authentication or redirection to be successful."

The exact same code works perfectly, when I do a simple HTTP GET, but when I throw in some POST params, everything fails.

Any ideas?

Answer

Tommi Forsström picture Tommi Forsström · Apr 21, 2009

I am ever so happy! I found the answer to my question!!!

This little line did the trick:

((HttpWebRequest)rqst).AllowWriteStreamBuffering = true;