需求:数据对接接口为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);
}
对方接受的传参类型是application/x-www-form-urlencoded,传参用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;
}
}
暂无评论
要发表评论,您必须先 登录