user385048
user385048

Reputation: 111

Asynchronous I/O (reading stream from asynchronous webrequest)

I'm running into a bit of problem when trying to post data asynchronously. Here's the code:

    public string PostHTTP(string http, string data)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(http);
        postData = data;
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.BeginGetResponse(new AsyncCallback(GetRequestStreamCallback), request);
        allDone.WaitOne();
        Referer = http;
        return information;
    }

    private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        Stream postStream = request.EndGetRequestStream(asynchronousResult); //Here is problem
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        postStream.Write(byteArray, 0, postData.Length);
        postStream.Close();
        request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
    }

The error I'm receiving is:

Unable to cast object of type 'System.Net.HttpWebResponse' to type 'System.Exception'.

What is the problem?

Upvotes: 0

Views: 682

Answers (2)

TLiebe
TLiebe

Reputation: 7986

Have a look at the sample here. Try calling EndGetResponse on your request object instead of EndGetRequestStream. Then, if that executes successfully, you can call GetResponseStream.

Upvotes: 1

Jeff Mercado
Jeff Mercado

Reputation: 134841

In your PostHTTP() method, you called BeginGetResponse() yet in the callback you use EndGetRequestStream(). These are completely different operations. Shouldn't you be using EndGetResponse()? Or at least start off with BeginGetRequest()?

Upvotes: 1

Related Questions