tok*_*oki 11 upload android progress httpclient httpurlconnection
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, 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);
}
Run Code Online (Sandbox Code Playgroud)
对于任何文件大小,此代码都可以快速执行,但该文件实际上仍在上传到服务器,我从服务器获得响应.HttpURLConnection当我调用时,它似乎在内部缓冲区中缓存所有数据out.write().
那么,我怎样才能获得实际的文件上传进度?似乎httpclient可以做到这一点,但
httpclient不是首选...任何想法?
tok*_*oki 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.
Run Code Online (Sandbox Code Playgroud)
setFixedLengthStreamingMode()先打电话解决我的问题.但正如这篇文章所提到的,android中存在一个错误,HttpURLConnection即使setFixedLengthStreamingMode()已经调用了缓存所有内容,直到后froyo才会修复.所以我使用HttpClient代替预姜饼.
| 归档时间: |
|
| 查看次数: |
4478 次 |
| 最近记录: |