工具類的代碼如下:
package utils; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class HttpRequest { /** * 從網絡Url中下載文件 * @param urlStr * @param fileName * @param savePath * @throws IOException */ public static File downLoadFromUrl(String urlStr,String fileName,String savePath) { InputStream inputStream = null; FileOutputStream fos = null; try { URL url = new URL(urlStr); 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("lfwywxqyh_token",toekn);*/ //得到輸入流 inputStream = conn.getInputStream(); //獲取自己數組 byte[] getData = readInputStream(inputStream); //文件保存位置 File saveDir = new File(savePath); //如果不存在目錄,則創建 if(!saveDir.exists()){ saveDir.mkdir(); } //路徑+分隔符+文件名 File file = new File(saveDir + File.separator + fileName); fos = new FileOutputStream(file); fos.write(getData); System.out.println("下載文件成功"); return file; }catch (Exception e){ return null; }finally { //必須關流 if(fos != null){ try { fos.close(); }catch (Exception e){ System.out.println("fos關流失敗"); } } if(inputStream != null){ try { inputStream.close(); }catch (Exception e){ System.out.println("inputStream關流失敗"); } } } } /** * 從輸入流中獲取字節數組 * @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(); } }