用于读取大流的 HttpWebRequest 和 Response
我有一个要求,我需要从网络服务器读取大流或数据。 这不是流式传输,而是从客户端分块读取大数据。
为此,我创建了一个 Http Web 请求。以下是示例代码。
StreamingObject streamObj = null;
using (HttpWebRequest httpReq = WebRequest.Create(uri))
{
HttpWebResponse response = httpReq.GetRespons();
Stream responseStream = response.GetStream();
streamObj = new StreamingObject(response, responseStream);
}
return streamObj;
在我的代码中,我向给定的 Uri 发出 Http Web 请求。然后我得到 HttpWebResponse 和响应流。创建 StreamingObject 的实例,它是用于存储 Http 响应和响应流的包装类。
我已经处理了 Http Web 请求。为客户端提供了 StreamingObject,并且流对象具有一种返回底层响应流的 GetStream 方法。当 StreamingObject 被释放时,Http 响应和流也被释放。
引入 StreamingObject 的原因是 Http Response 必须保持打开状态才能访问底层流。
我想知道这是否是正确的方法或者有更简单的方法。
I have a requirement where I need to read large stream or data from a web server.
This is not streaming but reading large data in chunks from the client side.
For this purpose I create an Http Web Request. Following is the sample code..
StreamingObject streamObj = null;
using (HttpWebRequest httpReq = WebRequest.Create(uri))
{
HttpWebResponse response = httpReq.GetRespons();
Stream responseStream = response.GetStream();
streamObj = new StreamingObject(response, responseStream);
}
return streamObj;
In my code I make a Http Web request to given Uri. Then I get the HttpWebResponse and the Response Stream. Create an instance of StreamingObject which is a wrapper class for storing the Http response and the response stream.
I have disposed the Http Web Request. The client is provided with the StreamingObject and the streaming object has one method GetStream which returns the underlying response stream. When the StreamingObject is disposed the Http response and the stream is disposed.
The reason for introducing the StreamingObject was that the Http Response has to be kept open for accessing the underlying stream.
I wish to know whether this is a correct approach or there is simpler way of doing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议不要处置 HttpWebRequest 对象,因为您可能非常需要它。只需将其添加到
StreamingObject
中,并在处置StreamingObject
时处置它。例如,我发现如果我想提前关闭响应流,响应将挂起,直到读取所有数据。但是在请求对象上调用Abort
将立即关闭流。I would suggest not disposing of the
HttpWebRequest
object, because you might very well need it. Just add it toStreamingObject
and dispose of it when you dispose of theStreamingObject
. For example, I've found that if I want to close the response stream prematurely, the response will hang until all of the data has been read. But callingAbort
on the request object will immediately close the stream.