根据文件地址下载文件,返回byte字节数组

根据网络文件地址下载文件,返回byte字节数组

/**
     * 下载网络文件
     * @param filePath
     * @return
     * @throws BusinessException
     */
    public  byte[] dowloadWebFile(String filePath) throws BusinessException {
        try {
            URL url = new URL(filePath);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3*1000);
            //防止屏蔽程序抓取而返回403错误
//            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //设置请求头
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] bs = readInputStream(inputStream);
            return bs;
        } catch (Exception e) {
            // TODO: handle exception
            throw new BusinessException(ErrorEnum.ERROR_SYSTEM,"下载附件异常:"+e.getMessage());
        }
    }
/** 
    * 从输入流中获取字节数组 
    * @param inputStream 
    * @return 
    * @throws IOException 
    */  
   public static  byte[] readInputStream(InputStream inputStream) throws IOException {    
       byte[] buffer = new byte[1024];    
       int len = 0;    
       ByteArrayOutputStream bos = new ByteArrayOutputStream();    
       while((len = inputStream.read(buffer)) != -1) {
           bos.write(buffer, 0, len);    
       }    
       bos.close();    
       return bos.toByteArray();    
   }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章