Android SSL双向认证HttpsURLConnection
2016-12-15 19:02
375 查看
public static String httpsPostServerWithCert(String url, String xml, Activity act) { KeyManagerFactory keyManager = null; try { keyManager = KeyManagerFactory.getInstance("X509"); } catch (NoSuchAlgorithmException e1) { // TODO e1.printStackTrace(); } KeyStore keyKeyStore = null; try { keyKeyStore = KeyStore.getInstance("BKS"); } catch (KeyStoreException e1) { // TODO e1.printStackTrace(); } FileInputStream kIs = null; try { kIs = new FileInputStream(""); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { keyKeyStore.load(kIs, null/* KSPWD.toCharArray() */); try { kIs.close(); } catch (IOException e2) { // TODO e2.printStackTrace(); } } catch (NoSuchAlgorithmException e2) { // TODO e2.printStackTrace(); } catch (CertificateException e2) { // TODO e2.printStackTrace(); } catch (IOException e2) { // TODO e2.printStackTrace(); } try { keyManager.init(keyKeyStore, null/* KSPWD.toCharArray() */); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } // /////////////////////////////////////////// TrustManagerFactory trustManager = null; try { trustManager = TrustManagerFactory.getInstance("X509"); } catch (NoSuchAlgorithmException e1) { // TODO e1.printStackTrace(); } KeyStore trustKeyStore = null; try { trustKeyStore = KeyStore.getInstance("BKS"); } catch (KeyStoreException e1) { // TODO e1.printStackTrace(); } InputStream tkIS = null; try { // tkIS = new FileInputStream("mPath"); tkIS = act.getResources().openRawResource(R.raw.client); } catch (Exception e1) { // TODO e1.printStackTrace(); } try { trustKeyStore.load(tkIS, null/* TKSPWD.toCharArray() */); tkIS.close(); trustManager.init(trustKeyStore); } catch (NoSuchAlgorithmException e1) { // TODO e1.printStackTrace(); } catch (CertificateException e1) { // TODO e1.printStackTrace(); } catch (IOException e1) { // TODO e1.printStackTrace(); } catch (KeyStoreException e) { // TODO e.printStackTrace(); } catch (Exception e) { // TODO e.printStackTrace(); } SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("TLS"); sslContext.init(null/* keyManager.getKeyManagers() */, trustManager.getTrustManagers(), null); } catch (NoSuchAlgorithmException e) { // TODO e.printStackTrace(); } catch (KeyManagementException e) { // TODO e.printStackTrace(); } String str = null; try { SSLSocket socket = (SSLSocket) sslContext.getSocketFactory() .createSocket("", 110); PrintWriter out = null; try { out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.println(xml); } catch (IOException e) { e.printStackTrace(); } out.flush(); out.close(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader( socket.getInputStream())); do { String v = in.readLine(); if (v == null) { break; } str += new String(v.getBytes(), "utf-8"); } while (true); in.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (UnknownHostException e) { // TODO e.printStackTrace(); } catch (IOException e) { // TODO e.printStackTrace(); } return str; } // 证书 private X509TrustManager xtm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) { } public void checkServerTrusted(X509Certificate[] chain, String authType) { System.out.println("cert: " + chain[0].toString() + ", authType: " + authType); } public X509Certificate[] getAcceptedIssuers() { return null; } }; public void testConn(String strurl, String xml, Activity act){ try { // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); X509TrustManager[] xtmArray = new X509TrustManager[]{xtm}; context.init( null , xtmArray , null); HttpsURLConnection.setDefaultHostnameVerifier(hnv); // Tell the URLConnection to use a SocketFactory from our SSLContext URL url = new URL(strurl); HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection(); urlConnection.setSSLSocketFactory(context.getSocketFactory()); urlConnection.connect(); InputStream in = urlConnection.getInputStream(); // copyInputStreamToOutputStream(in, System.out); byte[] bys = new byte[200]; System.out.println("in.available() ==> "+in.available()); int l = -1; StringBuffer sbf = new StringBuffer(); while ((l= in.read(bys))!=-1){ sbf.append(new String(bys, 0, l,"utf-8")); } System.out.println("get string is ===> "+sbf.toString()); } catch (Exception e) { // TODO e.printStackTrace(); } } private static final String KEY_PWD = "123456"; public static String httpsPostServer(String strurl, String xml, Activity act) throws Exception { URL url = null; StringBuffer sb = new StringBuffer(); // TrustManagerFactory trustManager = null; // try { // trustManager = TrustManagerFactory.getInstance("X509"); // } catch (NoSuchAlgorithmException e1) { // // TODO // e1.printStackTrace(); // } // // KeyStore trustKeyStore = null; // try { // trustKeyStore = KeyStore.getInstance("BKS"); // } catch (KeyStoreException e1) { // // TODO // e1.printStackTrace(); // } // // InputStream tkIS = null; // try { // // tkIS = new FileInputStream("mPath"); // tkIS = act.getResources().openRawResource(R.raw.client); // // } catch (Exception e1) { // // TODO // e1.printStackTrace(); // } // // try { //// trustKeyStore.load(tkIS, null/* TKSPWD.toCharArray() */); // tkIS.close(); //// trustManager.init(trustKeyStore); // } catch (IOException e1) { // // TODO // e1.printStackTrace(); // } catch (Exception e) { // // TODO // e.printStackTrace(); // } /////////////////////////////////////////////////////////////// KeyManagerFactory keyManager = null; try { keyManager = KeyManagerFactory.getInstance("X509"); } catch (NoSuchAlgorithmException e1) { // TODO e1.printStackTrace(); } KeyStore keyKeyStore = null; try { keyKeyStore = KeyStore.getInstance("BKS"); } catch (KeyStoreException e1) { // TODO e1.printStackTrace(); } InputStream kIs = null; try { kIs =act.getResources().openRawResource(R.raw.client); } catch (Exception e1) { e1.printStackTrace(); } try { keyKeyStore.load(kIs, KEY_PWD.toCharArray()); try { kIs.close(); } catch (IOException e2) { // TODO e2.printStackTrace(); } } catch (NoSuchAlgorithmException e2) { // TODO e2.printStackTrace(); } catch (CertificateException e2) { // TODO e2.printStackTrace(); } catch (IOException e2) { // TODO e2.printStackTrace(); } try { keyManager.init(keyKeyStore, KEY_PWD.toCharArray()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("TLS"); // X509TrustManager[] xtmArray = new X509TrustManager[]{xtm}; sslContext.init(keyManager.getKeyManagers(),null// trustManager.getTrustManagers() , new java.security.SecureRandom()); if (sslContext != null) { HttpsURLConnection.setDefaultSSLSocketFactory(sslContext .getSocketFactory()); } HttpsURLConnection.setDefaultHostnameVerifier(hnv); url = new URL(strurl); HttpsURLConnection connection = (HttpsURLConnection) url .openConnection(); // connection.setRequestProperty("User-Agent", // "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); connection.setDoOutput(true);// 设置是否可以输出流 connection.setRequestMethod("POST");// 设置提交方式为post // connection.setRequestProperty("Pragma:", "no-cache"); connection.setRequestProperty("Cache-Control", "no-cache"); connection.setRequestProperty("Error-State", "200 OK"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setConnectTimeout(20000);// 设置超时 connection.setReadTimeout(20000); // 输出流,向服务器端发信息, OutputStreamWriter osw = new OutputStreamWriter( connection.getOutputStream()); osw.write(new String(xml.getBytes("utf-8"))); osw.flush(); osw.close(); Log.i("test", "得到输出流:" + connection.getReadTimeout()); // 获取服务端发过来的信息 InputStreamReader isr = new InputStreamReader( connection.getInputStream(), "utf-8"); BufferedReader br = new BufferedReader(isr); String line = ""; // 循环读取服务器发送过来的信息 Log.i("test", "开始:" + connection.getReadTimeout() + "--" + connection.getConnectTimeout()); for (line = br.readLine(); line != null; line = br.readLine()) { sb.append(line); Log.i("test", line); } } catch (Exception e) { e.printStackTrace(); throw e; } return sb.toString(); } private static HostnameVerifier hnv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { System.out.println("hostname: " + hostname); return true; } };
相关文章推荐
- Android 让WebView完美支持https双向认证(SSL)
- IOS Android Tomcat SSL双向认证HTTPS访问
- "Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list.xml,reason: Connection
- android 让webview支持https 双向认证(SSL)
- Android 让WebView完美支持https双向认证(SSL)
- 关于双向认证,使用HttpsURLConnection访问Https安全链接
- Android 让WebView完美支持https双向认证(SSL)
- android SSL证书认证、SSL双向认证、https访问;
- Android webview在https下实现ssl的双向认证
- android 让webview支持https 双向认证(SSL)
- IOS Android Tomcat SSL双向认证HTTPS访问
- Failed to fetch URL https://dl-ssl.google.com/android/repository/repository-6.xml, reason: Connection to https://dl-ssl.google.com refused
- android 让webview支持https 双向认证(SSL)
- "Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list.xml,reason: Connection
- android 让webview支持https 双向认证(SSL)
- 解决:Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_li ..
- Failed to fectch URl https://dl-ssl.google.com/android/repository/addons_list-2.xml
- Android SDK Manager更新错误,Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list
- Failed to fectch URl https://dl-ssl.google.com/android/repository/addons_list.xml, reason: Connectio