在 Android 中发布大文件

发布于 2024-10-08 00:07:08 字数 540 浏览 0 评论 0原文

在 Android 中发布大文件时,我有时会遇到 OutOfMemoryError。这是我正在使用的代码。我做错了什么吗?

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
ostream = new DataOutputStream(con.getOutputStream());
byte[] buffer = new byte[1536];
int count;
while ((count = fileInput.read(buffer)) != -1) {
    ostream.write(buffer, 0, count); // This sometimes causes OutOfMemoryError
}
ostream.flush();

在 while 循环中调用 ostream.flush() 会有什么好处吗?

I sometimes get an OutOfMemoryError when posting a large file in Android. This is the code I'm using. Am I doing something wrong?

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
ostream = new DataOutputStream(con.getOutputStream());
byte[] buffer = new byte[1536];
int count;
while ((count = fileInput.read(buffer)) != -1) {
    ostream.write(buffer, 0, count); // This sometimes causes OutOfMemoryError
}
ostream.flush();

Would calling ostream.flush() inside the while loop do any good?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

酒中人 2024-10-15 00:07:08

如果你这样做,整个 POST 必须缓冲在内存中。这是因为它需要先发送 Content-Length 标头。

相反,我认为您想使用 Apache HTTP 库,包括 文件实体。这将让它在读取文件之前计算出长度。您可以使用此答案作为一个起点。但 FileEntity 构造函数的第二个参数应该是 mime 类型(如 image/png、text/html 等)。

If you do it like that, the whole POST must be buffered in memory. This is because it needs to send the Content-Length header first.

Instead, I think you want to use the Apache HTTP libraries, including FileEntity. That will let it figure out the length before reading the file. You can use this answer as a starting point. But the second parameter to the FileEntity constructor should be a mime type (like image/png, text/html, etc.).

≈。彩虹 2024-10-15 00:07:08

HTTP 连接没问题,但 HTTPS 会触发 Out of Memory 错误,因为 Android 2.3.4 中的 HttpsURLConnectionImpl.java 存在 bug(在我的平板电脑上验证),在 Android 4.1 中已修复(我已检查源代码)。

顺便说一句,他应该通过添加“con.setChunkedStreamingMode(0);”来避免在 RAM 中缓冲整个 POST 数据。紧接在“con.setDoOutput(true);”之后陈述。

HTTP connection is fine, but HTTPS will trigger Out of Memory error because there is a bug in HttpsURLConnectionImpl.java in Android 2.3.4 (verified on my tablet), and it's fixed in Android 4.1 (I have checked the source code).

By the way, he should avoid buffering the whole POST data in RAM by adding "con.setChunkedStreamingMode(0);" immediately after "con.setDoOutput(true);" statement.

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