使用 HttpURLConnection 流式传输数据
我想使用 HttpURLConnection 通过 HTTP POST 打开与服务器的长期连接,并处理传入的流数据。这是针对 Android 项目的。
我不清楚如何使用 HttpURLConnection 执行此操作。在 iOS 中,NSURLConnection 提供了一种异步模式,当新数据进入并可用于解析时,将调用用户实现的回调。
通过 Java 中的 HttpURLConnection,我看到有一个 available() 方法返回可以读取的字节数。但是,目前还不清楚我将如何编写一个流应用程序,该应用程序打开连接并在新的流数据可用于解析 DataInputStream 时做出反应。
我希望得到一些意见。 HttpURLConnection 或 Java 中的替代类是否支持 HTTP 连接的非阻塞、异步处理?
谢谢
I want to use HttpURLConnection to open a long-living connection to a server via HTTP POST and process streaming data as it comes in. This is for an Android project.
It's unclear to me how to do this with HttpURLConnection. In iOS, NSURLConnection provides an asynchronous mode where a user-implemented callback gets called as new data comes in and is available for parsing.
With the HttpURLConnection in Java, I see there's an available() method that returns the number of bytes that can be read. But, its unclear how I would write a streaming app that opens a connection and reacts as new streaming data becomes available to parse off a DataInputStream.
I would appreciate some input. Does HttpURLConnection or an alternate class in Java support non-blocking, asynchronous processing of HTTP connections?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
经过更多研究后,我确认 Java 没有任何对异步 HTTP 的内置支持。名为 Jetty 的软件包包含一个带有内置异步 HTTP 和回调的 HTTP 客户端。它位于:
http://wiki.eclipse.org/Jetty/Tutorial/HttpClient
After doing more research, I've confirmed that Java doesn't have any built-in support for asynchronous HTTP. A packaged called Jetty contains a HTTP client with built-in asynchronous HTTP and callbacks. Its available at:
http://wiki.eclipse.org/Jetty/Tutorial/HttpClient
创建一个扩展
Observable
并实现Runnable
的对象。您的主应用程序实现Observer
并将其自身作为观察者添加到您的新对象中。在新线程中运行您的对象。它会阻止对 HTTPUrlConneciton 的读取,并通知观察者刚刚读取的数据。
Create an Object that extends
Observable
and implementsRunnable
. Your main application implementsObserver
and adds itself to your new object as an observer.Run your object in a new thread. It does blocking reads on your HTTPUrlConneciton and notifies observers with the data that has just been read.
,没有。有一个 available() 方法,它返回可以在不阻塞的情况下读取的字节数。完全不是一回事。
HttpURLConnection 听起来不太适合这项任务。 HTTP 是一个请求-响应协议,而不是一个流协议,至少在 Java 类中实现是这样。
No there isn't. There is an available() method that returns the number of bytes that can be read without blocking. Not at all the same thing.
HttpURLConnection doesn't sound like a good fit for this task. HTTP is a request-response protocol, not a streaming protocol, at least as implemented in the Java classes.