banner
Matt

Matt

Matt-xlog
telegram
github

【JAVA】【工具类】信任SSL证书

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**

  • java 信任 SSL 证书 工具类

/
public class SslUtil {
//url 下载方法
public void downloadFileFromUrl(String fileUrl, String fileName) throws Exception {
URL url = new URL(fileUrl);
SslUtil.ignoreSsl();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(6000);
urlConnection.setReadTimeout(6000);
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println ("连接请求状态:---------------"+urlConnection.getResponseCode ());
throw new RuntimeException ("文件读取失败");
}
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int len;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.close();
File file = new File("/deployments/" + fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(byteArrayOutputStream.toByteArray());
fileOutputStream.close();
inputStream.close();
System.out.println ("下载成功:" + "/deployments/" + fileName);
}
/
*
* 忽略 HTTPS 请求的 SSL 证书,必须在 openConnection 之前调用
*
* @throws Exception
*/
public static void ignoreSsl() throws Exception {
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
}
private static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new miTM();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements TrustManager, X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}

	public boolean isServerTrusted(X509Certificate[] certs) {
		return true;
	}

	public boolean isClientTrusted(X509Certificate[] certs) {
		return true;
	}

	public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
		return;
	}

	public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
		return;
	}
}

}

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。