Java使用SSLContext请求https

发布时间 2023-06-03 15:19:57作者: 云里雾里的测试

//首先实现信任的管理器类

ublic class HttpsUtil {
 
    private static class TrustAnyTrustManager implements X509TrustManager {
 
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
 
        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
 
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    }
 
    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
 
public static byte[] post(String url, String content, String charset) {
       //获取一个SSLContext实例
       SSLContext s = SSLContext.getInstance("SSL")
       //初始化SSLContest.init(可以导入的证书,信任管理器,SecureRandom) 三个参数都可以为null, 没有证书的写null就行
       SSLContext.init(null, new TrustManager[]  {new TrustAnyTrustManager },  new java.security.SecureRandom());