今天在对接一个银商的项目接口,测试环境调用,在写调用util的时候,有一些证书相关问题。
对于http换成支持https调用,网上有很多类的重写方法。就不细说了。
先把代码贴一下:
(还有2个类,我稍微改下晚点补上代码~)
SSLClientUtil.java
package com.naka.fizzbuzz;
import java.net.Socket;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
public class SSLTrustClient extends SSLClient {
public SSLTrustClient() {
}
@Override
public void prepareCertificate() throws Exception {
// 跳过证书验证
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
SSLContext ctx = SSLContext.getInstance("TLS");
// 如果这里是,会报错:Algorithm constraints check failed on signature algorithm: MD5withRSA
X509TrustManager tm = new X509ExtendedTrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
// 设置成已信任的证书
ctx.init(null, new TrustManager[] { tm }, null);
this.connectionSocketFactory = new SSLConnectionSocketFactory(ctx, new HostnameVerifier(){
@Override
public boolean verify(String hostname, SSLSess