12

Android 开发者博客推荐使用HttpURLConnectionapache 以外的HttpClienthttp://android-developers.blogspot.com/2011/09/androids-http-clients.html)。我接受建议并在报告文件上传进度时遇到问题。

我获取进度的代码是这样的:</p>

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

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

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

4

2 回答 2

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()解决我的问题。但正如这篇文章所提到的,android 中有一个错误,HttpURLConnection即使setFixedLengthStreamingMode()已被调用,也会缓存所有内容,直到 post-froyo 才修复。所以我使用 HttpClient 代替预姜饼。

于 2013-08-13T08:49:31.243 回答
-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);
于 2013-08-07T09:55:35.253 回答