异步I / O(从异步webrequest读取流)

时间:2010-11-06 23:45:52

标签: c# httpwebrequest

尝试异步发布数据时遇到了一些问题。这是代码:

    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);
    }

我收到的错误是:

  

无法将“System.Net.HttpWebResponse”类型的对象强制转换为“System.Exception”。

有什么问题?

2 个答案:

答案 0 :(得分:1)

PostHTTP()方法中,您使用BeginGetResponse()在回调中调用了EndGetRequestStream()。这些是完全不同的操作。你不应该使用EndGetResponse()吗?或者至少从BeginGetRequest()开始?

答案 1 :(得分:1)

查看示例here。尝试在您的请求对象上调用EndGetResponse而不是EndGetRequestStream。然后,如果成功执行,您可以调用GetResponseStream