从开放的 HTTP 流中读取数据
我正在尝试使用 .NET WebRequest/WebResponse 类来访问此处的 Twitter 流 API "http://stream.twitter.com/spritzer.json"
。
我需要能够打开连接并从打开的连接中增量读取数据。
目前,当我调用 WebRequest.GetResponse
方法时,它会阻塞,直到下载整个响应。 我知道有一个 BeginGetResponse 方法,但这只会在后台线程上执行相同的操作。 我需要在下载仍在进行时访问响应流。 对于我来说,这些课程似乎不可能做到这一点。
Twitter 文档中有对此的具体评论:
“请注意,某些 HTTP 客户端库仅在服务器关闭连接后返回响应正文。这些客户端将无法访问 Streaming API。您必须使用例如,将增量返回响应数据的 HTTP 客户端将提供此功能。
他们指向 Appache HttpClient,但这并没有多大帮助,因为我需要使用 .NET。
有什么想法可以通过 WebRequest/WebResponse
实现这一点,还是我必须去学习较低级别的网络课程? 也许还有其他库可以让我做到这一点?
谢谢 艾伦
I am trying to use the .NET WebRequest/WebResponse classes to access the Twitter streaming API here "http://stream.twitter.com/spritzer.json"
.
I need to be able to open the connection and read data incrementally from the open connection.
Currently, when I call WebRequest.GetResponse
method, it blocks until the entire response is downloaded. I know there is a BeginGetResponse
method, but this will just do the same thing on a background thread. I need to get access to the response stream while the download is still happening. This just does not seem possible to me with these classes.
There is a specific comment about this in the Twitter documentation:
"Please note that some HTTP client libraries only return the response body after the connection has been closed by the server. These clients will not work for accessing the Streaming API. You must use an HTTP client that will return response data incrementally. Most robust HTTP client libraries will provide this functionality. The Apache HttpClient will handle this use case, for example."
They point to the Appache HttpClient, but that doesn't help much because I need to use .NET.
Any ideas whether this is possible with WebRequest/WebResponse
, or do I have to go for lower level networking classes? Maybe there are other libraries that will allow me to do this?
Thx
Allen
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我最终使用了 TcpClient,效果很好。 尽管如此,我仍然有兴趣知道这是否可以通过 WebRequest/WebResponse 实现。 这是我的代码,以防有人感兴趣:
I ended up using a TcpClient, which works fine. Would still be interested to know if this is possible with WebRequest/WebResponse though. Here is my code in case anybody is interested:
BeginGetResponse 是您需要的方法。 它允许您增量地读取响应流:
或者如果您觉得使用 WebClient (我个人更喜欢它而不是 WebRequest):
BeginGetResponse is the method you need. It allows you to read the response stream incrementally:
Or if you feel more comfortable with WebClient (I personnally prefer it over WebRequest):
我认为现代的方法是:
I think the modern way to do this is here:
您是否尝试过 WebRequest.BeginGetRequestStream() ?
或者是这样的:
Have you tried WebRequest.BeginGetRequestStream() ?
Or something like this: