okhttp3 https请求不需要证书

自测可用

1.证书类class

2.okhttp类class

public class SSLSocketClient {
    //获取这个SSLSocketFactory
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    //获取TrustManager
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) {
                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[]{}; //okhttp 3.0 以前版本

                     return new X509Certificate[0] ; //3.0后版本
                }
            }
        };
        return trustAllCerts;
    }
    //获取HostnameVerifier
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }
}

 

 

public class HttpUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
	
	private static final OkHttpClient client = new OkHttpClient().newBuilder()
			.connectTimeout(200, TimeUnit.SECONDS)  
            .readTimeout(200, TimeUnit.SECONDS) 
            .retryOnConnectionFailure(false)
            .sslSocketFactory(SSLSocketClient.getSSLScocketFactory())
            .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
            .build();  
	
	private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("application/json; charset=utf-8");

	private static final HttpUtil instance = new HttpUtil();
	
	private HttpUtil() {
		
	}
	
	public static HttpUtil getInstance() {
		return instance;
	}
	
	/**
	 * 执行http post请求
	 * @param postBody
	 * @param url
	 * @return
	 */
	public  String httpExecute(String postBody, String url,String tokenCode) {
		Request request = null ;
		
		if(tokenCode !=null && !"".equals(tokenCode)) {
			Headers headers = new Headers.Builder()
						.add("Authorization",tokenCode)
						.add("Content-type", "application/json;charset=utf-8")
						.build();
 	    	request = new Request.Builder().url(url)
                        .headers(headers)
 			            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
                        .build();
		}else {
			request = new Request.Builder()
					.url(url)
					.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
					.build();
		}

		try {
			System.out.println("request:"+ request);
			Response response = client.newCall(request).execute();
			logger.info("response:{}",response);
			
			return response.body().string();
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug(" 网络调用异常httpExecute : {}", e);
		}
		return null;
	}

	/**
	 * 转换成指定对象
	 * 
	 * @param postBody
	 * @param url
	 * @param clazz
	 * @return
	 * @throws IOException 
	 */
	public  Object  httpExecute(String postBody, String url, Class clazz,String tokenCode) {
	 
 		String 	rString = httpExecute(postBody, url,tokenCode);
        Object obj  = null ;
		try {
			 Object obj = JSONObject.parseObject(rString, clazz);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	
		return obj ;

	}
}

 

你可能感兴趣的:(okhttp3 https请求不需要证书)