setFixedLengthStreamingMode

setFixedLengthStreamingMode

本文介绍了有没有什么办法可以得到正确上传进度与HttpUrlConncetion的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android开发者博客推荐使用比Apache的的HttpURLConnection 的HttpClient (http://android-developers.blogspot.com/2011/09/androids-http-clients.html).我拿的意见并获得问题的报告文件上传进度。

Android Developers Blog recommend to use HttpURLConnection other than apache's HttpClient(http://android-developers.blogspot.com/2011/09/androids-http-clients.html). I take the adviceand get problem in reporting file upload progress.

我的code抢进度是这样的:

my code to grab progress is like this:

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

这code excutes非常快无论文件大小,但该文件实际上仍然上传到服务器UTIL我得到来自服务器的响应。似乎的HttpURLConnection 缓存的时候,我打电话内部缓冲区中的所有数据 out.write()

this code excutes very fast for whatever file size, but the file is actually still uploading to the server util i get response from the server. it seems that HttpURLConnection caches all data in internal buffer when i call out.write().

所以,我怎样才能得到实际的文件上传进度?好像的HttpClient 能做到这一点,但的HttpClient 不是prefered ...任何想法?

So, how can i get the actual file upload progress? Seems like httpclient can do that, buthttpclient is not prefered...any idea?

推荐答案

我发现开发者文档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()第一个解决我的问题。但是,所提到的这个帖子,也使得Android中的一个错误的HttpURLConnection 缓存所有内容,即使 setFixedLengthStreamingMode()被调用,这是不固定的,直到后期升级Froyo。所以我使用HttpClient的,而不是为pre-姜饼。

Calling setFixedLengthStreamingMode() first fix my problem.But as mentioned by this post, there is a bug in android that makes HttpURLConnection caches all content even if setFixedLengthStreamingMode() has been called, which is not fixed until post-froyo. So i use HttpClient instead for pre-gingerbread.

这篇关于有没有什么办法可以得到正确上传进度与HttpUrlConncetion的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:48