用于读取大流的 HttpWebRequest 和 Response

发布于 2024-10-21 17:34:21 字数 727 浏览 2 评论 0原文

我有一个要求,我需要从网络服务器读取大流或数据。 这不是流式传输,而是从客户端分块读取大数据。

为此,我创建了一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

〃安静 2024-10-28 17:34:21

我建议不要处置 HttpWebRequest 对象,因为您可能非常需要它。只需将其添加到 StreamingObject 中,并在处置 StreamingObject 时处置它。例如,我发现如果我想提前关闭响应流,响应将挂起,直到读取所有数据。但是在请求对象上调用 Abort 将立即关闭流。

I would suggest not disposing of the HttpWebRequest object, because you might very well need it. Just add it to StreamingObject and dispose of it when you dispose of the StreamingObject. 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 calling Abort on the request object will immediately close the stream.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文