2

我刚刚注意到 C# 中的一些行为让我有点失望。我正在使用 C# 5 和 .NET 4.5。当我在 HTTPResponse 对象上调用 GetResponseStream() 时,我能够获取响应流,但如果我在同一个对象上再次调用它,则响应为空白。

// Works! Body of the response is in the source variable.
HttpResponse response = (HttpWebResponse)request.GetResponse();
String source = new StreamReader(response.GetResponseStream()).ReadToEnd();

// Does Not Work. Source is empty;
String source2 = new StreamReader(response.GetResponseStream()).ReadToEnd();

以上只是演示问题的示例。

编辑

这就是我想要做的。基本上,如果一个事件附加到 HTTP 对象,它会将响应传递回回调方法。

HttpWebResponse public Get(String url)
{
    // HttpWebRequest ...

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // postRequest is an event handler. The response is passed to the
    // callback to do whatever it needs to do.
    if (this.postRequest != null)
    {
        RequestEventArgs requestArgs = new RequestEventArgs();
        requestArgs.source = response;
        postRequest.Invoke(this, requestArgs);
    }

    return response;
}

在回调方法中,我可能想检查响应的正文。如果这样做,当 Get() 返回响应时,我会丢失响应中的数据。

4

1 回答 1

8

响应流直接从网络连接中读取。

一旦你读到最后(在第 2 行),就没有更多数据要读取了。

于 2013-07-26T22:02:55.020 回答