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

用传统方法使用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();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值