1. 程式人生 > >android多執行緒下載-HttpURLConnection

android多執行緒下載-HttpURLConnection

android多執行緒下載-HttpURLConnection

private static String PATH = "http://192.168.37.2:8080/http/02.jpg";
    public static void main(String[] args) throws Exception {

        URL url = new URL(PATH);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();

        int
totalSize = conn.getContentLength(); int threadCount = 3; //計算每個位元組下載的位元組數 int blockSize = totalSize/3; //資源路徑 String path = PATH; //目標路徑 String target = "H://a.jpg"; for (int i = 1; i <= threadCount; i++) { int id = i; int
startIndex = (id-1)*blockSize; int endIndex = -1; if (id==threadCount) { //3*3-1 endIndex = totalSize-1; }else { endIndex = id*blockSize-1; } DownloadThread downloadThread = new DownloadThread(id,startIndex,endIndex,path,target); downloadThread.start(); } } static
class DownloadThread extends Thread{ private int id; private int startIndex; private int endIndex; private String path; private String target; public DownloadThread(int id, int startIndex, int endIndex,String path, String target) { super(); this.id = id; this.startIndex = startIndex; this.endIndex = endIndex; this.path = path; this.target = target; } @Override public void run() { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex); conn.connect(); int code = conn.getResponseCode(); if (206==code) { InputStream inputStream = conn.getInputStream(); File file = new File(target); RandomAccessFile raf = new RandomAccessFile(file ,"rwd"); raf.seek(startIndex); int len=-1; byte[] buffer = new byte[1024]; int total =0; while((len=inputStream.read(buffer))!=-1){ raf.write(buffer,0,len); total+=len; System.out.println(id+"下載了"+total); } System.out.println(id+"已完成"); raf.close(); } } catch (Exception e) { e.printStackTrace(); } } }