使用HttpURLConnection上传文件,进度条显示不正确

xiaoxiao2021-02-27  330

用传统方法使用HttpURLConnection进行上传时,进度条显示过快,达到100%之后会卡很长时间,其实此时还在上传。这是因为HttpURLConnection自己维护的一个缓存,先把要上传的数据写入缓存里,然后才传。而我们得到的进度却是写入缓存的进度,所以进度条会更新很快。可以通过下列方法禁掉缓存:

参考:http://blog.csdn.net/yinkai1205/article/details/7731705

总结:我们必须先禁止掉输出流的缓存,这样connection.connect();之后就实际建立网络连接,我们在while中测算上传进度,否则我们测算的上传进度只是写到缓存的进度,不是实际的上传进度

URL realUrl = new URL(req_url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); // set header connection.setReadTimeout(20*1000); connection.setConnectTimeout(10*1000);//理解为建立连接的超时时间 10S,不理解为总时间,因为测试发现写成100MS 也是OK的 connection.setRequestMethod("POST"); connection.setRequestProperty("accept", "*/*"); connection.setFixedLengthStreamingMode(totalLength); connection.setRequestProperty("Connection", "close"); connection.setUseCaches(false); connection.setAllowUserInteraction(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; charset=utf-8"); OutputStream out = new DataOutputStream(connection.getOutputStream()); int bytes = 0; byte[] bufferOut = new byte[1024]; int hasUpLoadCount=0; connection.connect(); while ((bytes = ins.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); out.flush(); hasUpLoadCount+=bytes; upPicListener.onUpProgress(hasUpLoadCount*100/totalLength); } out.close(); // read rsp String rsp = GetResponse(connection); //删除老的文件 file.delete();

转载请注明原文地址: https://www.6miu.com/read-3285.html

最新回复(0)