有没有办法使用HttpUrlConnection正确上传进度

时间:2013-08-07 09:46:57

标签: android upload httpclient httpurlconnection progress

Android开发者博客建议使用除{apache's HttpURLConnection以外的HttpClienthttp://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);
}

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

那么,我怎样才能获得实际的文件上传进度?似乎httpclient可以做到这一点,但是 httpclient不是首选......任何想法?

2 个答案:

答案 0 :(得分:15)

我在开发者文档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代替预姜饼。

答案 1 :(得分:-2)

使用Asynctask上传文件以将文件上传到服务器并创建Progressdialog

1)在

中运行您的代码
 doinbackground(){
    your code here..
}

2)更新

中的进度
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
    //type this in the while loop before write..

3)和更新进度

protected void onProgressUpdate(String... progress) {
            Progress.setProgress(Integer.parseInt(progress[0]));
        }

4)取消

中的进展
protected void onPostExecute(String file_url) {
            dismissDialog(progress);