1. 程式人生 > >jdk1.7 使用Protocol 版本為 TLSv1.2 異常:javax.net.ssl.SSLException: Received fatal alert: protocol_version

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;
    }