java根据一个远程地址将文件下载到本地
private void readFile(String docId, String token, String productResource, String docUrl){
        String url = thirdConfig.getAttachmentUrl() + docId;
        //下载资源
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        try {
            urlfile = new URL(url);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.setRequestProperty("Authorization",token);
            // 设置通用的请求属性
            httpUrl.setRequestProperty("accept", "*/*");
            httpUrl.setRequestProperty("connection", "Keep-Alive");
            httpUrl.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            httpUrl.connect();
            Map<String, List<String>> map = httpUrl.getHeaderFields();
            List<String> disposition = map.get("content-disposition");
            if(disposition == null){
                disposition = map.get("Content-Disposition");
            }
            if(disposition == null || disposition.size() <= 0){
                logger.info("------------disposition is null...");
                httpUrl.disconnect();
                return;
            }
            String filename = disposition.get(0);
            filename = filename.substring(filename.indexOf("=") + 1);
            filename = filename.replaceAll("\"", "");
            String name = java.net.URLDecoder.decode(filename,"UTF-8");
            String path = thirdConfig.getFilePath() + "/" + docId + "/" + name;
            File f = FileUtil.CreateFolderSystemPath(path);
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len ;
            byte[] b = new byte[2048];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            bos.close();
            bis.close();
            httpUrl.disconnect();
        }catch (Exception e){
            logger.error("--------------- download fail-------------: ");
            logger.error(e.getMessage());

        }finally {
            if (bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }

            if (bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }

            if(httpUrl != null){
                httpUrl.disconnect();
            }
        }
    }

  

posted on 2024-12-10 16:40  james-roger  阅读(5)  评论(0编辑  收藏  举报