HttpClient请求HTTPS报错javax.net.ssl.SSLException: hostname in certificate didn't match

时间:2022-08-12 18:05:06
首先写getSslsf()方法:    
private static SSLConnectionSocketFactory getSslsf() throws NoSuchAlgorithmException, KeyManagementException {
    	SSLContext sslContext = SSLContext.getInstance("SSL");//sslContext= SSLContext.getInstance("TLS");
	    X509TrustManager tm = new X509TrustManager() {  
	        
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {  

            }  

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {  
            }  

            public X509Certificate[] getAcceptedIssuers() {  
                return null;  
            }  
        };  
        sslContext.init(null, new TrustManager[] { tm }, null);
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        /*Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory> create()
        		 .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", sslsf).build();
        */
        return sslsf;
	}
再次创建HttpClients.custom().setSSLSocketFactory(getSslsf()).build()的httpClient;
CloseableHttpClient httpClient = null;
		HttpPost httpPost = null;
		try {
			
			httpClient = HttpClients.custom().setSSLSocketFactory(getSslsf()).build();//实例化HttpClients对象
			RequestConfig requestConfig = RequestConfig.custom()
					.setSocketTimeout(20000).setConnectTimeout(20000).build();//构建RequestConfig对象
			httpPost = new HttpPost(url);//构建HttpPost对象
			httpPost.setConfig(requestConfig);//设置RequestConfig
			/**
			 * 在请求正文中,可以随意的提交一段字符串给服务器,现在为了数据交换的统一性,所以大家都是提交的一段json串
			 * 所以body的数据格式{"name":"zhangsan","age":18},如果body是该数据格式,则Content-Type要设置为application/json
			 * new StringEntity(body)是指利用body构建一个请求正文对象,且StringEntity是支持Content-Type为application/json的,
			 * 所以,如果用StringEntity对象且body的数据为json串,则无需我们再设置Content-type
			 */
	        httpPost.setHeader("Content-Type","application/json");//setHeader是设置请求头,该句代码是设置Content-Type,要设置其它的请求头,也是setHeader方法
	        httpPost.setHeader("Connection","keep-alive");
	        httpPost.setEntity(new StringEntity(body));//设置请求正文,也就是设置json串
//			httpPost.setEntity(new StringEntity(body,"application/x-www-form-urlencoded"));//同上面两句代码一个意思
	        //SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
	        //SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocktFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			CloseableHttpResponse response = httpClient.execute(httpPost);
			HttpEntity httpEntity = response.getEntity();//获取响应正文对象
			String result = EntityUtils.toString(httpEntity,"utf-8");
			System.out.println("***"+result);
			return result;//按编码输出响应正文
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(httpPost !=null){
					httpPost.releaseConnection();
				}
				if(httpClient !=null){
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;