項目中Android https請求地址遇到了這個異常(無終端認證):
javax.net.ssl.SSLPeerUnverifiedException: No peer certificatejava
是SSL協議中沒有終端認證。android
沒有遇到過的問題,因而無奈的去找度娘。。。。。。。web
看了很多大神的博客後獲得的解決方案以下:算法
/** * Post請求鏈接Https服務 * @param serverURL 請求地址 * @param jsonStr 請求報文 * @return * @throws Exception */ public static synchronized String doHttpsPost(String serverURL, String jsonStr)throws Exception { // 參數 HttpParams httpParameters = new BasicHttpParams(); // 設置鏈接超時 HttpConnectionParams.setConnectionTimeout(httpParameters, 3000); // 設置socket超時 HttpConnectionParams.setSoTimeout(httpParameters, 3000); // 獲取HttpClient對象 (認證) HttpClient hc = initHttpClient(httpParameters); HttpPost post = new HttpPost(serverURL); // 發送數據類型 post.addHeader("Content-Type", "application/json;charset=utf-8"); // 接受數據類型 post.addHeader("Accept", "application/json"); // 請求報文 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對象 * @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); //容許全部主機的驗證 sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // 設置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下,小手發抖的點到測試按鈕,深吸口氣,咦?沒反應。。。馬蛋的,工做線程忘記start(),唉,再次run下,終於的有點反應了,神奇的居然沒有報以前的 javax.net.ssl.SSLPeerUnverifiedException: No peer certificate 的異常了。服務端的數據正常返回了。
1.peer終端發送一個request,https服務端把支持的加密算法等以證書的形式返回一個身份信息(包含ca頒發機構和加密公鑰等)。json
2.獲取證書以後,驗證證書合法性。瀏覽器
3.隨機產生一個密鑰,並以證書當中的公鑰加密。安全
4.request https服務端,把用公鑰加密過的密鑰傳送給https服務端。app
5.https服務端用本身的密鑰解密,獲取隨機值。socket
6.以後雙方傳送數據都用此密鑰加密後通訊。ide
HTTPS流程清楚後,問題也就明顯了,驗證證書時,沒法驗證。
上面提供的解決方案就是添加默認信任所有證書。以此來經過接下來的通訊。
可是,這樣問題是解決了。可是以爲仍是不帶靠譜(信任所有證書有點危險)。繼續噼噼啪啪的網上搜索一番。又找到了一種解決方案,其過程大體這樣的:
1.瀏覽器訪問https地址,保存提示的證書到本地,放到android項目中的assets目錄。
2.導入證書,代碼以下。
3.把證書添加爲信任。
public static String requestHTTPSPage(Context context, String mUrl) { InputStream ins = null; String result = ""; try { ins = context.getAssets().open("my.key"); // 下載的證書放到項目中的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; }