您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)android httpClient 支持HTTPS的訪問方式是怎樣的,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
項(xiàng)目中Android https請(qǐng)求地址遇到了這個(gè)異常(無終端認(rèn)證):
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
是SSL協(xié)議中沒有終端認(rèn)證。
沒有遇到過的問題,于是無奈的去找度娘。。。。。。。
看了不少大神的博客后得到的解決方案如下:
/** * Post請(qǐng)求連接Https服務(wù) * @param serverURL 請(qǐng)求地址 * @param jsonStr 請(qǐng)求報(bào)文 * @return * @throws Exception */ public static synchronized String doHttpsPost(String serverURL, String jsonStr)throws Exception { // 參數(shù) HttpParams httpParameters = new BasicHttpParams(); // 設(shè)置連接超時(shí) HttpConnectionParams.setConnectionTimeout(httpParameters, 3000); // 設(shè)置socket超時(shí) HttpConnectionParams.setSoTimeout(httpParameters, 3000); // 獲取HttpClient對(duì)象 (認(rèn)證) HttpClient hc = initHttpClient(httpParameters); HttpPost post = new HttpPost(serverURL); // 發(fā)送數(shù)據(jù)類型 post.addHeader("Content-Type", "application/json;charset=utf-8"); // 接受數(shù)據(jù)類型 post.addHeader("Accept", "application/json"); // 請(qǐng)求報(bào)文 StringEntity entity = new StringEntity(jsonStr, "UTF-8"); post.setEntity(entity); post.setParams(httpParameters); HttpResponse response = null; try { response = hc.execute(post); } catch (UnknownHostException e) { throw new Exception("Unable to access " + e.getLocalizedMessage()); } catch (SocketException e) { e.printStackTrace(); } int sCode = response.getStatusLine().getStatusCode(); if (sCode == HttpStatus.SC_OK) { return EntityUtils.toString(response.getEntity()); } else throw new Exception("StatusCode is " + sCode); } private static HttpClient client = null; /** * 初始化HttpClient對(duì)象 * @param params * @return */ public static synchronized HttpClient initHttpClient(HttpParams params) { if(client == null){ try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SSLSocketFactoryImp(trustStore); //允許所有主機(jī)的驗(yàn)證 sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // 設(shè)置http和https支持 SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { e.printStackTrace(); return new DefaultHttpClient(params); } } return client; } public static class SSLSocketFactoryImp extends SSLSocketFactory { final SSLContext sslContext = SSLContext.getInstance("TLS"); public SSLSocketFactoryImp(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted( java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted( java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } }; sslContext.init(null, new TrustManager[] { tm }, null); } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } }
run下,小手發(fā)抖的點(diǎn)到測(cè)試按鈕,深吸口氣,咦?沒反應(yīng)。。。馬蛋的,工作線程忘記start(),唉,再次run下,終于的有點(diǎn)反應(yīng)了,神奇的竟然沒有報(bào)之前的 javax.net.ssl.SSLPeerUnverifiedException: No peer certificate 的異常了。服務(wù)端的數(shù)據(jù)正常返回了。
分析問題:
HTTPS:超文本安全傳輸協(xié)議,和HTTP相比,多了一個(gè)SSL/TSL的認(rèn)證過程,端口為443。
1.peer終端發(fā)送一個(gè)request,https服務(wù)端把支持的加密算法等以證書的形式返回一個(gè)身份信息(包含ca頒發(fā)機(jī)構(gòu)和加密公鑰等)。
2.獲取證書之后,驗(yàn)證證書合法性。
3.隨機(jī)產(chǎn)生一個(gè)密鑰,并以證書當(dāng)中的公鑰加密。
4.request https服務(wù)端,把用公鑰加密過的密鑰傳送給https服務(wù)端。
5.https服務(wù)端用自己的密鑰解密,獲取隨機(jī)值。
6.之后雙方傳送數(shù)據(jù)都用此密鑰加密后通信。
HTTPS流程清楚后,問題也就明顯了,驗(yàn)證證書時(shí),無法驗(yàn)證。
上面提供的解決方案就是添加默認(rèn)信任全部證書。以此來通過接下來的通信。
但是,這樣問題是解決了。但是覺得還是不帶靠譜(信任全部證書有點(diǎn)危險(xiǎn))。繼續(xù)噼噼啪啪的網(wǎng)上搜索一番。又找到了一種解決方案,其過程大致這樣的:
1.瀏覽器訪問https地址,保存提示的證書到本地,放到android項(xiàng)目中的assets目錄。
2.導(dǎo)入證書,代碼如下。
3.把證書添加為信任。
public static String requestHTTPSPage(Context context, String mUrl) { InputStream ins = null; String result = ""; try { ins = context.getAssets().open("my.key"); // 下載的證書放到項(xiàng)目中的assets目錄中 CertificateFactory cerFactory = CertificateFactory.getInstance("X.509"); Certificate cer = cerFactory.generateCertificate(ins); KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC"); keyStore.load(null, null); keyStore.setCertificateEntry("trust", cer); SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore); Scheme sch = new Scheme("https", socketFactory, 443); HttpClient mHttpClient = new DefaultHttpClient(); mHttpClient.getConnectionManager().getSchemeRegistry().register(sch); BufferedReader reader = null; try { HttpGet request = new HttpGet(); request.setURI(new URI(mUrl)); HttpResponse response = mHttpClient.execute(request); if (response.getStatusLine().getStatusCode() != 200) { request.abort(); return result; } reader = new BufferedReader(new InputStreamReader(response .getEntity().getContent())); StringBuffer buffer = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } result = buffer.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (ins != null) ins.close(); } catch (IOException e) { e.printStackTrace(); } } return result;
關(guān)于android httpClient 支持HTTPS的訪問方式是怎樣的就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。