根據URL下載圖片到本地
阿新 • • 發佈:2019-01-30
/** * 根據URL下載圖片 * @throws IOException */ public static String savePicData(String urlLink,String dir,String pkid) throws Exception { System.out.println(urlLink); String[] typeList = urlLink.split("\\."); String type = typeList[typeList.length-1];//新增字尾 URL url = new URL(urlLink); //某些圖片訪問或者下載需要安全驗證 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn instanceof HttpsURLConnection) { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom()); ((HttpsURLConnection) conn).setSSLSocketFactory(sc.getSocketFactory()); ((HttpsURLConnection) conn).setHostnameVerifier(new TrustAnyHostnameVerifier()); } conn.connect(); System.out.println(conn.getResponseCode()); // 得到輸入流 java.io.InputStream inputStream = conn.getInputStream(); ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[100]; int rc = 0; while ((rc = inputStream.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); } // 獲取自己陣列 byte[] getData =swapStream.toByteArray(); // 檔案儲存位置 File saveDir = new File(dir); if (!saveDir.exists()) { saveDir.mkdirs(); } String path = saveDir + File.separator + pkid + "." + type; File file = new File(path); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } return path; } private static class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } } private static class TrustAnyHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; } }