android - 有什么方法可以使用 HttpUrlConnection 正确获取上传进度

标签 android upload httpclient httpurlconnection progress

Android 开发者博客建议使用 HttpURLConnection 而不是 apache 的 HttpClient (http://android-developers.blogspot.com/2011/09/androids-http-clients.html)。我接受建议 并在报告文件上传进度时遇到问题。

我的抓取进度代码是这样的:

try {
    out = conncetion.getOutputStream();
    in = new BufferedInputStream(fin);
    byte[] buffer = new byte[MAX_BUFFER_SIZE];
    int r;
    while ((r = in.read(buffer)) != -1) {
        out.write(buffer, 0, r);
        bytes += r;
        if (null != mListener) {
            long now = System.currentTimeMillis();
            if (now - lastTime >= mListener.getProgressInterval()) {
                lastTime = now;
                if (!mListener.onProgress(bytes, mSize)) {
                    break;
                }
            }
        }
    }
    out.flush();
} finally {
    closeSilently(in);
    closeSilently(out);
}

无论文件大小如何,此代码都执行得非常快,但文件实际上仍在上传到服务器实用程序,我从服务器获得响应。当我调用 out.write() 时,HttpURLConnection 似乎将所有数据缓存在内部缓冲区中。

那么,如何获取实际的文件上传进度呢?似乎 httpclient 可以做到这一点,但是 httpclient 不是首选...知道吗?

最佳答案

我在开发者文档中找到了解释http://developer.android.com/reference/java/net/HttpURLConnection.html

To upload data to a web server, configure the connection for output using setDoOutput(true).
For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.

调用 setFixedLengthStreamingMode() 首先解决我的问题。 但正如this post提到的, android 中有一个错误使得 HttpURLConnection 缓存所有内容,即使 setFixedLengthStreamingMode() 已被调用,直到 post-froyo 才修复。所以我使用 HttpClient 代替预 Gingerbread 。

关于android - 有什么方法可以使用 HttpUrlConnection 正确获取上传进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18100096/

相关文章:

Java - 为什么 HttpClient 不发送我的 cookie?

android - 更改 ListView 中 TextView 的可见性

python - 使用 Tornado 将 Zip 文件上传到服务器时损坏

html - 上传前显示图片预览

使用 AngularJS(Java 配置)上传 Spring Rest Multipart 文件?

android - HttpPost cookie 持久化 android

android - 如何获取android互联网连接状态?

android - 带有多个按钮的通知

android - SpotsDialog 在 'dmax.dialog.SpotsDialog 中具有私有(private)访问权限

delphi - 如何在delphi 10中跟踪NetHttpClient上传的进度?