使用 HttpURLConnection 流式传输数据

发布于 2024-10-27 23:19:28 字数 403 浏览 1 评论 0原文

我想使用 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 技术交流群。

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

发布评论

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

评论(3

千纸鹤 2024-11-03 23:19:28

经过更多研究后,我确认 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

水中月 2024-11-03 23:19:28

创建一个扩展 Observable 并实现 Runnable 的对象。您的主应用程序实现 Observer 并将其自身作为观察者添加到您的新对象中。

在新线程中运行您的对象。它会阻止对 HTTPUrlConneciton 的读取,并通知观察者刚刚读取的数据。

Create an Object that extends Observable and implements Runnable. Your main application implements Observer 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.

一绘本一梦想 2024-11-03 23:19:28

有一个 available() 方法
返回可以的字节数
被阅读

,没有。有一个 available() 方法,它返回可以在不阻塞的情况下读取的字节数。完全不是一回事。

HttpURLConnection 听起来不太适合这项任务。 HTTP 是一个请求-响应协议,而不是一个流协议,至少在 Java 类中实现是这样。

there's an available() method that
returns the number of bytes that can
be read

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.

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