TSL協議升級導致的問題:caught when processing request: Received fatal alert: protocol_version


近日,公司升級TSL協議,禁用TSL1.0,導致原本好好的https接口,報以下錯誤:

2019-03-05 15:43:29 [org.apache.commons.httpclient.HttpMethodDirector]-[INFO] - I/O exception (javax.net.ssl.SSLException) caught when processing request: Received fatal alert: protocol_version

 

解決方案:

把原來TSLv1.0協議升級成1.1  or1.2即可。

        SSLContext sslContext = SSLContexts.custom().useTLS().build();
        SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null,
                null);
        CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(f).build();

直接貼修改前后的代碼:

原始使用的HttpClient版本叫老,默認1.0,且沒有重新設置TSL協議版本的地方;為了升級,使用CloseableHttpClient ,且引入SSLContext 。

修改前:

public static String postJosnOld(String url,String jsonString) throws Exception{ HttpClient client = new HttpClient(); PostMethod myPost = new PostMethod(url); //設置請求超時時間 15秒
        client.getHttpConnectionManager().getParams().setConnectionTimeout(15000); String responseString = null; //設置請求頭部類型 
        myPost.setRequestHeader("Content-Type","application/json;charset=utf-8"); myPost.setRequestHeader("charset","utf-8"); myPost.setRequestEntity(new StringRequestEntity(jsonString,"text/json","utf-8")); int statusCode = client.executeMethod(myPost); if(statusCode == HttpStatus.SC_OK){ BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream()); byte[] bytes = new byte[1024]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); int count = 0; while((count = bis.read(bytes))!= -1){ bos.write(bytes, 0, count); } byte[] strByte = bos.toByteArray(); responseString = new String(strByte,0,strByte.length,"utf-8"); bos.close(); bis.close(); } myPost.releaseConnection(); return responseString; }

 

修改后:

    public static String postJosn(String url, String jsonString) throws Exception { SSLContext sslContext = SSLContexts.custom().useTLS().build(); SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null, null); CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(f).build(); HttpPost myPost = new HttpPost(url); myPost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8"); myPost.setHeader("charset", "utf-8"); StringEntity s = new StringEntity(jsonString, "utf-8"); s.setContentEncoding("UTF-8"); s.setContentType("application/json;charset=utf-8"); myPost.addHeader("Content-Type", "application/json;charset=utf-8"); myPost.setEntity(s); HttpResponse res = client.execute(myPost); HttpEntity entity = res.getEntity(); myPost.releaseConnection(); return EntityUtils.toString(entity, "utf-8"); }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM