参考文章https://blog.csdn.net/shumeng_xiaoyan/article/details/76503601 步骤1,实现自己的x509TrustManager类,并复写三种方法 public class My509TrustManager 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 new X509Certificate[0]; } } 步骤2
TrustManager[] tm={new My509TrustManager();//1.生成trustmanager数组 SSLContext ssl=SSLContext.getInstance("TLS"); //2.得到sslcontext实例。SSL TSL 是一种https使用的安全传输协议 ssl.init(null,tm,new SecureRandom());//初始化sslcontext SSLSocketFactory sslSocketFactory=ssl.getSocketFactory();//得到sslSocketFactory实例 URL url=new URL(urlpath); HttpsURLConnection connection=(HttpsURLConnection) url.openConnection(); connection.setRequestMethod(requestmethod); connection.setSSLSocketFactory(sslSocketFactory);//设置sllsocketfactory connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("content-type","application/json; charset=UTF-8"); connection.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; } }); connection.connect(); String strJson=getJsonData(); OutputStream out=connection.getOutputStream(); if(out!=null&&strJson!=null&&!TextUtils.isEmpty(strJson)){ out.write(strJson.getBytes("UTF-8")); }