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

 项目依赖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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值