根據網絡文件地址下載文件,返回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(); }