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();
            }

        }

    }

猜你喜欢

转载自blog.csdn.net/AliEnCheng/article/details/78446239