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

前端之家收集整理的这篇文章主要介绍了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代替姜饼前.

原文链接:https://www.f2er.com/android/313365.html

猜你在找的Android相关文章