問題
oauth授權認證方式對接第三方平台,使用httpclient訪問對方服務器,執行execute函數請求,java拋出異常,java.net.SocketException: Connection reset 這是雙方握手建立連接后,開始write數據被服務器斷開連接了,返回復位標志 RST關閉了連接並拋出了異常,感覺很奇怪,於是使用postman模擬表單提交請求獲取對方令牌通過了,那可能是自己這邊代碼問題了,后來發現代碼在請求http時是可用的,但請求https就會報錯 connection rest ,查閱資料發現這是jdk的一個bug,已經在jdk8_141之后修復

所以,如果項目能升級到jdk8_141版本后,https請求的問題基本就能解決了,但公司項目使用的代碼版本是jdk7_80的,如果為了我一個接口冒然升級那風險無疑是很大的。
解決
jdk7默認支持TLS是V1,jdk8后默認支持的是V1.2,所以在發起socket請求時指定協議為1.2,即可在不升級jdk的請求下解決這個問題
/** * * Description: 解決jdk 1.7版本訪問https * @author willem * @date 2022/3/17 */ private static SSLConnectionSocketFactory getSslConnectionSocketFactory() { return new SSLConnectionSocketFactory(SSLContexts.createDefault()){ @Override protected void prepareSocket(SSLSocket socket) { String hostname = socket.getInetAddress().getHostName(); if (hostname.endsWith("www.baidu.com")){ socket.setEnabledProtocols(new String[] {"TLSv1.2"}); } else { socket.setEnabledProtocols(new String[] {"TLSv1", "TLSv1.1", "TLSv1.2"}); } } }; }
發送post請求
public static String post(String url, String client_id, String client_secret,String grant_type,String code,String redirect_uri,String scope) throws ClientProtocolException, IOException, NoSuchAlgorithmException { String jsonStr = ""; SSLConnectionSocketFactory sslsf = getSslConnectionSocketFactory(); CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); String requestBody = createRequestBody(client_id, client_secret,grant_type,code,redirect_uri,scope); HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); StringEntity entity = new StringEntity(requestBody); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); jsonStr = EntityUtils.toString(response.getEntity()); return jsonStr; }
成功獲取了第三方平台的令牌和授權,引起這個原因也有可能其他問題導致,如按本方案不能解決,請查閱其他資料。
