HTTPS要求証明書検証を無視
1730 ワード
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"));
}