Android断点续传

本文详细介绍了如何使用HTTP协议的POST方法发送XML数据,并实现文件的上传过程。
 1     public void sendMsgAndgetMsg() {
 2 
 3         HttpURLConnection connection = null;
 4         RandomAccessFile randomAccessFile = null;
 5         InputStream is = null;
 6 
 7         try {
 8             String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?></test>testxml-content<test>";
 9             byte[] byteXml = xml.getBytes("UTF-8");
10             URL url = new URL(urlStr);
11 
12             int compeleteSize = 0;
13             
14             Log.d(TAG, "run:url====>>" + url.toString());
15             
16             connection = (HttpURLConnection) url.openConnection();
17             connection.setConnectTimeout(5000);
18             connection.setRequestMethod("POST");
19             connection.setRequestProperty("Connection", "Keep-Alive");
20             connection.setDoInput(true);
21             connection.setRequestProperty("Content-Length", String.valueOf(byteXml.length));
22             connection.setRequestProperty("Range", "bytes=" + (0 + compeleteSize) + "-" + 6382170);
23             
24             DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
25             outStream.write(byteXml);// 发送xml数据
26             outStream.flush();
27             outStream.close();
28             // 设置范围,格式为Range:bytes x-y;
29             
30             randomAccessFile = new RandomAccessFile(new File(SD_PATH), "rwd");
31             randomAccessFile.seek(compeleteSize);
32             
33             Log.d(TAG, "con.getContentLength()====>>" + connection.getContentLength());
34             // 将要下载的文件写到保存在保存路径下的文件中
35             is = connection.getInputStream();
36             
37             byte[] buffer = new byte[4096];
38             int length = -1;
39             while ((length = is.read(buffer)) != -1) {
40                 randomAccessFile.write(buffer, 0, length);
41                 compeleteSize += length;
42                 // 更新数据库中的下载信息
43             }
44         } catch (Exception e) {
45             e.printStackTrace();
46         } finally {
47             try {
48                 is.close();
49                 randomAccessFile.close();
50                 connection.disconnect();
51             } catch (Exception e) {
52                 e.printStackTrace();
53             }
54         }
55     }

 

转载于:https://www.cnblogs.com/liqikuan/archive/2012/11/18/2776439.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值