原文地址:https://blog.csdn.net/csdn_terence/article/details/79244768
一個讀取網(wǎng)絡(luò)路徑和本地路徑 圖片的例子(親測可用)
需求:
1.讀取https酱吝、http類型氓癌,以及本地類型的圖片击纬。
其中,加載https類型的圖片時不能沿用http的獲取方法,否則會報“unable to find valid certification path to requested target ”的錯誤。
具體原因是,因?yàn)閔ttps(http+SSL)簡單講是http的安全版,即http下加入SSL層厅各,https的安全基礎(chǔ)是SSL,因此加密的詳細(xì)內(nèi)容就需要SSL晃琳。
解決辦法:此處使用https的Get請求來解決證書驗(yàn)證的問題讯检。
2.用日志記錄相關(guān)信息(引入commons-logging-1.1.jar包)
3.為了安全 ,對結(jié)果數(shù)據(jù)進(jìn)行編碼卫旱、解碼,
問題:
首先為什么BASE64Encoder和BASE64Decoder在Eclipse中不能使用围段?
? ? ? ?編碼解碼使用sun包下的BASE64Encoder和BASE64Decoder兩個工具把任意序列的8位字節(jié)描述為一種不易被人直接識別的形式顾翼;但不能使用是因?yàn)樗麄兪荢un公司專用的API,在Eclipse后來的版本中都不能直接使用奈泪,但是直接使用文本編輯器編寫代碼适贸,然后使用javac編譯,java去執(zhí)行是沒有問題的涝桅。
怎么設(shè)置才可以在Eclipse中使用BASE64Encoder和BASE64Decoder拜姿?
? ? ? ?右擊項(xiàng)目 --> Properties --> Java Build Path --> 點(diǎn)開JRE SystemLibrary --> 點(diǎn)擊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));
}
/*
* 讀取遠(yuǎn)程和本地文件圖片
*/
public static String readImg(String urlOrPath){
? ? ? ? InputStream in = null;
? ? ? ? try {
? ? ? ? ? byte[] b ;
? ? ? //加載https途徑的圖片(要避開信任證書的驗(yàn)證)
? ? ? ? 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); //調(diào)用方法,得到輸出流的字節(jié)數(shù)組
return base64ToStr(b);? ? //調(diào)用方法冯遂,為防止異常 蕊肥,得到編碼后的結(jié)果
? ? ? ? } catch (Exception e) {
? ? ? ? log.error("讀取圖片發(fā)生異常:"+ e);
? ? ? ? return "error";
? ? ? ? }
? ? }
public static byte[] getByte(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
byte[] buf=new byte[1024]; //緩存數(shù)組
while(in.read(buf)!=-1){ //讀取輸入流中的數(shù)據(jù)放入緩存,如果讀取完則循環(huán)條件為false;
out.write(buf); //將緩存數(shù)組中的數(shù)據(jù)寫入out輸出流蛤肌,如果需要寫到文件壁却,使用輸出流的其他方法
}
out.flush();
return out.toByteArray(); //將輸出流的結(jié)果轉(zhuǎn)換為字節(jié)數(shù)組的形式返回 (先執(zhí)行finally再執(zhí)行return )
} finally{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}
}
/*
* 編碼
* Base64被定義為:Base64內(nèi)容傳送編碼被設(shè)計用來把任意序列的8位字節(jié)描述為一種不易被人直接識別的形式
*/
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: 實(shí)現(xiàn)https請求,可用于加載https路徑的存儲圖片裸准,避開信任證書的驗(yàn)證展东。
*/
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());
? }
}
---------------------
作者:Terence_Jing
來源:CSDN
原文:https://blog.csdn.net/csdn_terence/article/details/79244768
版權(quán)聲明:本文為博主原創(chuàng)文章,轉(zhuǎn)載請附上博文鏈接炒俱!