jdk1.7 使用Protocol 版本为 TLSv1.2 异常:javax.net.ssl.SSLException: Received fatal alert: protocol_version...

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

 项目依赖JAVA 7,其中httpclient 使用的是 commons-httpclient3.0.jar 这个包已经十多年没有更新了。尝试了各种方法不能把Protocol 版本改为 TLSv1.2。最终无奈换commons-httpclient-3.1.jar 改为使用 httpclient-4.5.2.jar。、然后使用下面的方式可以让jdk1.7 使用Protocol 版本为 TLSv1.2

    /**
     * @Description: http post json 请求
     * @Author: 张颖辉(yh)
     * @Date: 2019/5/8 10:45
     * @param: [uri 请求地址, requestBody 请求json内容, timeOut 超时时间:毫秒]
     * @return: java.lang.String
     * @Version: 1.0
     */
    public static String executePost(String uri, String requestBody, Integer timeOut) throws NoSuchAlgorithmException, KeyManagementException {
       
//        SSLContext ctx= SSLContext.getInstance("TLSv1.2");
//        ctx.init(null, null, null);
        SSLContext ctx = SSLContexts.custom().useProtocol("TLSv1.2").build();
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(ctx)).build();
        HttpPost httpPost = new HttpPost(uri);
        String strResult = null;
        try {
            //httpPost.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8));
            HttpEntity httpEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
            httpPost.setEntity(httpEntity);
            /*连接超时*/
            if (null != timeOut) {
                RequestConfig requestConfig = RequestConfig.custom()
                        .setConnectTimeout(timeOut).setConnectionRequestTimeout(timeOut)
                        .setSocketTimeout(timeOut).build();
                httpPost.setConfig(requestConfig);
            }
            HttpResponse httpResponse = httpClient.execute(httpPost);
            logger.info("responseCode:{}", httpResponse.getStatusLine().getStatusCode());
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                strResult = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");//获得返回的结果
                logger.info("post请求返回信息为:{}", strResult);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();//释放资源
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return strResult;
    }

 

转载于:https://my.oschina.net/iyinghui/blog/3046893

你可能感兴趣的:(jdk1.7 使用Protocol 版本为 TLSv1.2 异常:javax.net.ssl.SSLException: Received fatal alert: protocol_version...)