根据URL下载图片到本地

/**
     * 根据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;
        }
    }

猜你喜欢

转载自blog.csdn.net/csdnwsf/article/details/82187445