java 加載https/http/本地類型路徑的圖片

一個讀取網絡路徑和本地路徑 圖片的例子(親測可用)

需求:

1.讀取https、http類型,以及本地類型的圖片。

其中,加載https類型的圖片時不能沿用http的獲取方法,否則會報unable to find valid certification path to requested target 的錯誤。

具體原因是,因爲https(http+SSL)簡單講是http的安全版,即http下加入SSL層,https的安全基礎是SSL,因此加密的詳細內容就需要SSL。

解決辦法:此處使用https的Get請求來解決證書驗證的問題。

2.用日誌記錄相關信息(引入commons-logging-1.1.jar包

3.爲了安全 ,對結果數據進行編碼、解碼,

問題:

首先爲什麼BASE64Encoder和BASE64Decoder在Eclipse中不能使用?

       編碼解碼使用sun包下的BASE64Encoder和BASE64Decoder兩個工具把任意序列的8位字節描述爲一種不易被人直接識別的形式;但不能使用是因爲他們是Sun公司專用的API,在Eclipse後來的版本中都不能直接使用,但是直接使用文本編輯器編寫代碼,然後使用javac編譯,java去執行是沒有問題的。

怎麼設置纔可以在Eclipse中使用BASE64Encoder和BASE64Decoder?

       右擊項目 --> Properties --> Java Build Path --> 點開JRE SystemLibrary --> 點擊Access rules --> Edit --> Add --> Resolution選擇Accessible--> Rule Pattern 填** --> OK

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class TestReadImgWithUrlOrPath {
	public static Log log=LogFactory.getLog(TestReadImgWithUrlOrPath.class);

	public static void main(String s[]) throws IOException
	{
		String urlOrPath="C:\\Users\\files\\Pictures\\kaola.jpg";
		
		//String urlOrPath="http://pic4.nipic.com/20091217/3885730_124701000519_2.jpg";
		System.out.println(urlOrPath);
		System.out.println(readImg(urlOrPath));
		
	}
	/*
	 * 讀取遠程和本地文件圖片
	 */
	public static String readImg(String urlOrPath){
        InputStream in = null;
        try {
          byte[] b ;
       //加載https途徑的圖片(要避開信任證書的驗證)
         if(urlOrPath.toLowerCase().startsWith("https")){
            b=HttpsUtils.doGet(url);
         }else if(urlOrPath.toLowerCase().startsWith("http")){ 
          //加載http途徑的圖片
            	URL url = new URL(urlOrPath);
    			in = url.openStream();    			           	
            }else{ //加載本地路徑的圖片
                File file = new File(urlOrPath);
                if(!file.isFile() || !file.exists() || !file.canRead()){
                    log.info("圖片不存在或文件錯誤");
                    return "error";
                }                
                in = new FileInputStream(file);
            }
            b = getByte(in); //調用方法,得到輸出流的字節數組
			return base64ToStr(b);    //調用方法,爲防止異常 ,得到編碼後的結果

        } catch (Exception e) {
        	log.error("讀取圖片發生異常:"+ e);
        	return "error";
        }
    }
	
	public static byte[] getByte(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();		
		try {
			byte[] buf=new byte[1024]; //緩存數組
			while(in.read(buf)!=-1){ //讀取輸入流中的數據放入緩存,如果讀取完則循環條件爲false;
				out.write(buf); //將緩存數組中的數據寫入out輸出流,如果需要寫到文件,使用輸出流的其他方法
				}
			out.flush();
			return out.toByteArray();	//將輸出流的結果轉換爲字節數組的形式返回	(先執行finally再執行return	)
		} finally{
			if(in!=null){
					in.close();
			}
			if(out!=null){
				out.close();
			}			
		}
	}
	
	/*
	 * 編碼
	 * Base64被定義爲:Base64內容傳送編碼被設計用來把任意序列的8位字節描述爲一種不易被人直接識別的形式
	 */
	public static String base64ToStr(byte[] bytes) throws IOException {
		String content = "";
		content = new BASE64Encoder().encode(bytes);
		return content.trim().replaceAll("\n", "").replaceAll("\r", ""); //消除回車和換行
	}
	/*
	 * 解碼
	 */
	public static byte[] strToBase64(String content) throws IOException {
		if (null == content) {
			return null;
		}
		return new BASE64Decoder().decodeBuffer(content.trim());
	}

}
import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @desc: 實現https請求,可用於加載https路徑的存儲圖片,避開信任證書的驗證。
 */
public class HttpsUtils {
  private static final class DefaultTrustManager implements X509TrustManager {
	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
	  return null;
	}
  }

  private static HttpsURLConnection getHttpsURLConnection(String uri, String method) throws IOException {
	SSLContext ctx = null;
	try {
	  ctx = SSLContext.getInstance("TLS");
	  ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
	} catch (KeyManagementException e) {
	  e.printStackTrace();
	} catch (NoSuchAlgorithmException e) {
	  e.printStackTrace();
	}
	SSLSocketFactory ssf = ctx.getSocketFactory();

	URL url = new URL(uri);
	HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
	httpsConn.setSSLSocketFactory(ssf);
	httpsConn.setHostnameVerifier(new HostnameVerifier() {
	  @Override
	  public boolean verify(String arg0, SSLSession arg1) {
		return true;
	  }
	});
	httpsConn.setRequestMethod(method);
	httpsConn.setDoInput(true);
	httpsConn.setDoOutput(true);
	return httpsConn;
  }

  private static byte[] getBytesFromStream(InputStream is) throws IOException {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	byte[] kb = new byte[1024];
	int len;
	while ((len = is.read(kb)) != -1) {
	  baos.write(kb, 0, len);
	}
	byte[] bytes = baos.toByteArray();
	baos.close();
	is.close();
	return bytes;
  }

  private static void setBytesToStream(OutputStream os, byte[] bytes) throws IOException {
	ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
	byte[] kb = new byte[1024];
	int len;
	while ((len = bais.read(kb)) != -1) {
	  os.write(kb, 0, len);
	}
	os.flush();
	os.close();
	bais.close();
  }

  public static byte[] doGet(String uri) throws IOException {
	HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "GET");
	return getBytesFromStream(httpsConn.getInputStream());
  }

  public static byte[] doPost(String uri, String data) throws IOException {
	HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "POST");
	setBytesToStream(httpsConn.getOutputStream(), data.getBytes());
	return getBytesFromStream(httpsConn.getInputStream());
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章