android – 有没有办法通过HttpUrlConncetion正确上传进度

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,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);
}

代码对于任何文件大小都非常快速地排除,但是该文件实际上仍然上传到服务器util,从服务器获取响应.当我调用out.write()时,似乎HttpURLConnection缓存了内部缓冲区中的所有数据.

那么,我如何获得实际的文件上传进度?似乎像httpclient可以做到这一点,但是
http客户端不受欢迎…任何想法?

解决方法

我发现开发者文档 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中出现了一个bug,即使调用了setFixedLengthStreamingMode(),即使在post-froyo之后,它仍然是固定的,所以使HttpURLConnection缓存所有的内容.所以我用HttpClient代替姜饼前.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...