如何阅读HttpWebResponse两次

时间:2016-08-27 12:36:18

标签: c# .net streamreader webrequest httpwebresponse

如何阅读HttpWebResponse twise?它有可能吗?

我的代码无效,respStream.Position = 0;无效。

任何线索,请?

var data = (HttpWebRequest)WebRequest.Create(url);  
var response = (HttpWebResponse)data.GetResponse();

var respStream = response.GetResponseStream();

string responseText;         
using (var reader = new StreamReader(respStream, encoding))
{
     responseText = reader.ReadToEnd().Trim();
}
// Do something and read it again
using (var reader = new StreamReader(respStream, encoding))
{
     responseText = reader.ReadToEnd().Trim();
}

2 个答案:

答案 0 :(得分:2)

response.GetResponseStream()返回的类型为System.Net.ConnectStream。如果您检查此流的属性CanSeek,您将看到它无法搜索,因此这意味着您无法重置并再次阅读:

var typeOfStream = respStream.GetType();    // System.Net.ConnectStream
var canSeek = respStream.CanSeek;           // false

但是,当您将数据读取到字符串时,您已经拥有了数据,因此您可以使用它两次:

string responseText1, responseText2;
using (var reader = new StreamReader(respStream, encoding))
{
     responseText1 = reader.ReadToEnd().Trim();
     responseText2 = responseText1;    // you get a copy of response
}

答案 1 :(得分:1)

我有一个类似的问题,但是我的流不包含字符串内容,而是二进制数据。由于我们只能读取一次ConnectStream,所以我的解决方案是将其复制到MemoryStream:

WebRequest request = WebRequest.Create("http://www.foo.bar/binary.file");
using (WebResponse response = request.GetResponse())
{
    var responseStream = response.GetResponseStream();

    using (var memoryStream = new MemoryStream())
    {
        responseStream.CopyTo(memoryStream);

        // This one is important so we can read the stream from the beginning.
        memoryStream.Seek(0, SeekOrigin.Begin); 

        // Perform my first thing.
        var isValid = Utility.ValidateContent(memoryStream);

        if (isValid)
        {
            // Reset the position to the beginning of the stream again
            memoryStream.Seek(0, SeekOrigin.Begin); 
            using (var fileStream = File.Create("c:\\temp\\myfile.ext"))
            {
                memoryStream.CopyTo(fileStream);
            }
        }
    }
}

要明确的是,如果只需要两倍于字符串数据的字符串,那么“ dotnetom”提供的解决方案既干净又快捷。