Post、Get請求Https,SSL證書的問題


最近在和第三方廠家進行數據對接,需要統一認證走單點登錄,就涉及到調用統一認證平台的接口,由於平台提供的接口為https,導致在請求的時候一直會因為SSL證書的校驗出錯,因此需要跳過SSL證書的校驗,步驟如下

第一步,新建一個類


代碼如下:

public class TrustAllTrustManager implements TrustManager, X509TrustManager {

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        return;
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        return;
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

第二步,在建立URLConnection之前就進行SSL證書的忽略,寫一個方法

代碼如下

private void skipSslValidation() throws NoSuchAlgorithmException, KeyManagementException {
        //默認使用本地
        HostnameVerifier hv = new HostnameVerifier() {
            @Override
            public boolean verify(String urlHostName, SSLSession session) {
                return true;
            }
        };
        TrustManager[] trustAllCerts = {new TrustAllTrustManager()};
        SSLContext sc = SSLContext.getInstance("SSL");
        SSLSessionContext sslsc = sc.getServerSessionContext();
        sslsc.setSessionTimeout(0);
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        //  激活主機認證
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

第三步,GET請求調用


代碼如下

private String getUserInfo(String userUrl) {
        String returnStr = null;
        try {
            //解決SSL驗證的問題
            skipSslValidation();
            URL url = new URL(userUrl);
            HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

            InputStream inStream = con.getInputStream();
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            byte[] b = outStream.toByteArray();
            outStream.close();
            inStream.close();
            returnStr = new String(b,"utf-8");
        } catch (Exception e) {
            logger.error(AuthExceptionMsg.GET_USER_INFO_ERROR.getMsg(),e.getMessage());
            throw new ServiceException(AuthExceptionMsg.GET_USER_INFO_ERROR);
        }
        return returnStr;
    }

第四步,Post請求調用

剛好本次調用第三方接口時,對方接受的傳參類型是application/x-www-form-urlencoded,平常寫application/json比較多,發現這種方式還是有點區別,傳參用key=value的方式,並且參數之間用&拼接,有點類似GET請求,因此一起記錄下來


代碼如下

private String getCodeToToken(AuthRequestForm authRequestForm) {
        String result = "";
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("grant_type",ssoLoginConfig.getGrantType());
        hashMap.put("client_id",ssoLoginConfig.getClientId());
        hashMap.put("client_secret",ssoLoginConfig.getClientSecret());
        hashMap.put("redirect_uri",authRequestForm.getRedirectUri());
        hashMap.put("code",authRequestForm.getCode());
        StringBuffer params = new StringBuffer();
        for (HashMap.Entry<String, Object> e : hashMap.entrySet()) {
            params.append(e.getKey());
            params.append("=");
            params.append(e.getValue());
            params.append("&");
        }
        URL reqURL;
        try {
            //跳過SSL驗證
            skipSslValidation();
            reqURL = new URL(ssoLoginConfig.tokenUrl);
            HttpURLConnection httpsConn = (HttpsURLConnection)reqURL.openConnection();
            httpsConn.setDoOutput(true);
            httpsConn.setRequestMethod("POST");
            httpsConn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            httpsConn.setRequestProperty("Accept-Charset", "utf-8");
            httpsConn.setRequestProperty("contentType", "utf-8");
            httpsConn.setRequestProperty("Content-Length", params.length() + "");
            OutputStreamWriter out = new OutputStreamWriter(httpsConn.getOutputStream(),"utf-8");
            out.write(params.toString());
            out.flush();
            out.close();
            //取得該連接的輸入流,以讀取響應內容
            InputStreamReader inputStreamReader = new InputStreamReader(httpsConn.getInputStream(),"utf-8");
            int respInt = inputStreamReader.read();
            while(respInt != -1) {
                result = result + (char) respInt;
                respInt = inputStreamReader.read();
            }
        } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {
            logger.error(AuthExceptionMsg.CODE_TO_TOKEN_ERROR.getMsg(), e.getMessage());
            throw new ServiceException(AuthExceptionMsg.CODE_TO_TOKEN_ERROR);
        }
        if (StringUtils.isEmpty(result)){
            return null;
        }else {
            return result;
        }
    }

以上就是所有記錄。


免責聲明!

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



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