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

原文地址: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)載請附上博文鏈接炒俱!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末盐肃,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子权悟,更是在濱河造成了極大的恐慌砸王,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,542評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件僵芹,死亡現(xiàn)場離奇詭異处硬,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)拇派,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,596評論 3 385
  • 文/潘曉璐 我一進(jìn)店門荷辕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來凿跳,“玉大人,你說我怎么就攤上這事疮方】厥龋” “怎么了?”我有些...
    開封第一講書人閱讀 158,021評論 0 348
  • 文/不壞的土叔 我叫張陵骡显,是天一觀的道長疆栏。 經(jīng)常有香客問我,道長惫谤,這世上最難降的妖魔是什么壁顶? 我笑而不...
    開封第一講書人閱讀 56,682評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮溜歪,結(jié)果婚禮上若专,老公的妹妹穿的比我還像新娘。我一直安慰自己蝴猪,他們只是感情好调衰,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,792評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著自阱,像睡著了一般嚎莉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上沛豌,一...
    開封第一講書人閱讀 49,985評論 1 291
  • 那天趋箩,我揣著相機(jī)與錄音,去河邊找鬼琼懊。 笑死阁簸,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的哼丈。 我是一名探鬼主播启妹,決...
    沈念sama閱讀 39,107評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼醉旦!你這毒婦竟也來了饶米?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,845評論 0 268
  • 序言:老撾萬榮一對情侶失蹤车胡,失蹤者是張志新(化名)和其女友劉穎檬输,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體匈棘,經(jīng)...
    沈念sama閱讀 44,299評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡丧慈,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,612評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片逃默。...
    茶點(diǎn)故事閱讀 38,747評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡鹃愤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出完域,到底是詐尸還是另有隱情软吐,我是刑警寧澤,帶...
    沈念sama閱讀 34,441評論 4 333
  • 正文 年R本政府宣布吟税,位于F島的核電站凹耙,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏肠仪。R本人自食惡果不足惜肖抱,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,072評論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望异旧。 院中可真熱鬧虐沥,春花似錦、人聲如沸泽艘。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,828評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽匹涮。三九已至,卻和暖如春槐壳,著一層夾襖步出監(jiān)牢的瞬間然低,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,069評論 1 267
  • 我被黑心中介騙來泰國打工务唐, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留雳攘,地道東北人。 一個月前我還...
    沈念sama閱讀 46,545評論 2 362
  • 正文 我出身青樓枫笛,卻偏偏與公主長得像吨灭,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子刑巧,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,658評論 2 350

推薦閱讀更多精彩內(nèi)容