public class HttpsUtils { private static HttpsUtils httpUtils; private HttpsUtils() { } public static HttpsUtils getInstance() { if (httpUtils == null) { httpUtils = new HttpsUtils(); } return httpUtils; } public interface OnRequestCallBack { void onSuccess(String s); void onFail(Exception e); } /** * 检测网络状态(true、可用 false、不可用) */ public static boolean checkNetState(Context context) { //修复bug connManager.getActiveNetworkInfo().isAvailable();会造成空指针 加一层try catch保证不会崩溃 try { ConnectivityManager connManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connManager.getActiveNetworkInfo() != null) { return connManager.getActiveNetworkInfo().isAvailable(); } return false; } catch (Exception e) { return false; } } public void get(final Context context, final String path, final OnRequestCallBack callBack, boolean isOpenProgressbar) { // 网络检查 if (!checkNetState(context)) { Toast.makeText(context, "网络不可用", Toast.LENGTH_SHORT) .show(); return; } // 是否显示进度条 if (isOpenProgressbar) { //TODO } new Thread(new Runnable() { @Override public void run() { HttpsURLConnection conn = null; InputStream inputStream = null; try { URL url = new URL(path); conn = (HttpsURLConnection) url.openConnection(); SSLContext tls = SSLContext.getInstance("TLS"); MyX509TrustManager myX509TrustManager = new MyX509TrustManager(getX509Certificate(context)); TrustManager[] trustManagers = {myX509TrustManager}; tls.init(null, trustManagers, new SecureRandom()); SSLSocketFactory factory = tls.getSocketFactory(); //添加一个主机名称校验器 conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { //TODO证书名称 if (hostname.equals("xxx")) { return true; } else { return false; } } }); conn.setSSLSocketFactory(factory); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); conn.connect(); inputStream = conn.getInputStream(); StringBuilder sb = new StringBuilder(); int flag; byte[] buf = new byte[1024]; while ((flag = inputStream.read(buf)) != -1) { sb.append(new String(buf, 0, flag)); } String s = sb.toString(); callBack.onSuccess(s); } catch (Exception e) { e.printStackTrace(); callBack.onFail(e); } finally { if (conn != null) { conn.disconnect(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }).start(); } public void post(final Context context, final String path, final Map params, final OnRequestCallBack callBack) { new Thread(new Runnable() { @Override public void run() { HttpsURLConnection conn = null; InputStream inputStream = null; OutputStream outputStream = null; try { URL url = new URL(path); conn = (HttpsURLConnection) url.openConnection(); SSLContext tls = SSLContext.getInstance("TLS"); MyX509TrustManager myX509TrustManager = new MyX509TrustManager(getX509Certificate(context)); TrustManager[] trustManagers = {myX509TrustManager}; tls.init(null, trustManagers, new SecureRandom()); SSLSocketFactory factory = tls.getSocketFactory(); //添加一个主机名称校验器 conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { //TODO证书名称 if (hostname.equals("xxxxx")) { return true; } else { return false; } } }); conn.setSSLSocketFactory(factory); conn.setRequestMethod("POST"); conn.setConnectTimeout(10 * 1000); conn.connect(); inputStream = conn.getInputStream(); JSONObject jsonObject = new JSONObject(params); byte[] bytes = jsonObject.toString().getBytes(); conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); conn.setRequestProperty("Cache-Control", "max-age=0"); conn.setRequestProperty("Content-Type", "application/Json; charset=UTF-8"); conn.setRequestProperty("Origin", path); conn.setDoOutput(true); outputStream = conn.getOutputStream(); outputStream.write(bytes); outputStream.flush(); StringBuilder sb = new StringBuilder(); int flag; byte[] buf = new byte[1024]; while ((flag = inputStream.read(buf)) != -1) { sb.append(new String(buf, 0, flag)); } String s = sb.toString(); callBack.onSuccess(s); } catch (Exception e) { e.printStackTrace(); callBack.onFail(e); } finally { if (conn != null) { conn.disconnect(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }).start(); } //拿到自己的证书 private X509Certificate getX509Certificate(Context context) throws IOException, CertificateException { InputStream in = context.getAssets().open("srca.cer"); CertificateFactory instance = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) instance.generateCertificate(in); return certificate; } }
public class MyX509TrustManager implements X509TrustManager { //如果需要对证书进行校验,需要这里去实现,如果不实现的话是不安全 X509Certificate mX509Certificate; public MyX509TrustManager(X509Certificate mX509Certificate) { this.mX509Certificate = mX509Certificate; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { for (X509Certificate certificate:chain){ //检查证书是否有效 certificate.checkValidity(); try { certificate.verify(mX509Certificate.getPublicKey()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } } } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }