TSL协议升级导致的问题:caught when processing request: Received fatal alert: protocol_version

时间:2023-03-09 22:29:19
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

TSL协议升级导致的问题: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");
}