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 }