Android开发者博客推荐使用HttpURLConnection,而不是apache的HttpClient
( http://android-developers.blogspot.com/2011/09/androids-http-clients.html).我接受建议
并在报告文件上传进度时遇到问题.
( 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缓存了内部缓冲区中的所有数据.
解决方法
我发现开发者文档
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代替姜饼前.