http下载

private static String getPath(String downUrl) throws Exception{
        
        URL url = new URL(downUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.addRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
        conn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) " +
                "Chrome/28.0.1500.72 Safari/537.36");
        
        conn.setConnectTimeout(300000);
        conn.setReadTimeout(300000);

        int state = conn.getResponseCode();
        
        if (state != 200) {
            return null;
        }
        File file = null;
        FileOutputStream output = null;
        String savePath = "E:/baseurl/app/360";
        file = new File(savePath);
        if(!file.exists())
            file.mkdirs();
        
        file = new File(file, getRandom() + "");
        if (!file.exists())
            file.mkdir();
        file = new File(file, "0.apk");
        output = new FileOutputStream(file);
        DownloadLimiter dl = new DownloadLimiter(conn.getInputStream(),
                new BandwidthLimiter(10240));
        byte buffer[] = new byte[1024 * 256];
        int readSize = 0;
        while ((readSize = dl.read(buffer)) != -1) {
            output.write(buffer, 0, readSize);
        }
        output.flush();
        output.close();
        dl.close();
        
        return file.getAbsolutePath();
    }

 

posted @ 2016-03-19 15:09  phyxis_xu  阅读(306)  评论(0编辑  收藏  举报