wisdomisite-java/src/main/java/com/zhgd/xmgl/util/X509TrustManagerUtil.java

194 lines
6.4 KiB
Java
Raw Normal View History

2024-03-08 09:55:19 +08:00
package com.zhgd.xmgl.util;
2024-04-14 21:05:01 +08:00
import lombok.extern.slf4j.Slf4j;
2024-03-08 09:55:19 +08:00
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* 处理https/http的图片
2024-03-08 09:55:19 +08:00
*/
2024-04-14 21:05:01 +08:00
@Slf4j
2024-03-08 09:55:19 +08:00
public class X509TrustManagerUtil implements X509TrustManager {
/**
* 从网络的url图片保存在本地包含http和https的图片下载
*/
public static void downLoadFromUrl(String urlStr, String fileName,
String savePath) throws Exception {
URL url = new URL(urlStr);
if (url.openConnection() instanceof HttpsURLConnection) {
downLoadFromUrlHttps(urlStr, fileName, savePath);
} else {
downLoadFromUrlHttp(urlStr, fileName, savePath);
}
}
2024-03-08 09:55:19 +08:00
/**
* 从网络的url图片保存在本地
*
* @param urlStr
* @param fileName
* @param savePath
* @throws Exception
*/
public static void downLoadFromUrlHttps(String urlStr, String fileName,
String savePath) throws Exception {
// 创建SSLContext
SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManager[] tm = {new X509TrustManagerUtil()};
// 初始化
sslContext.init(null, tm, new java.security.SecureRandom());
// 获取SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
// url对象
URL url = new URL(urlStr);
// 打开连接
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
/**
* 这一步的原因: 当访问HTTPS的网址您可能已经安装了服务器证书到您的JRE的keystore
* 但是服务器的名称与证书实际域名不相等这通常发生在你使用的是非标准网上签发的证书
*
* 解决方法让JRE相信所有的证书和对系统的域名和证书域名
*
* 如果少了这一步会报错:java.io.IOException: HTTPS hostname wrong: should be <localhost>
*/
conn.setHostnameVerifier(new X509TrustManagerUtil().new TrustAnyHostnameVerifier());
// 设置一些参数
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置当前实例使用的SSLSoctetFactory
conn.setSSLSocketFactory(ssf);
conn.connect();
// 得到输入流
FileOutputStream fos = null;
InputStream inputStream = null;
try {
inputStream = conn.getInputStream();
byte[] getData = readInputStream(inputStream);
// 文件保存位置
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdirs();
}
//输出流
File file = new File(saveDir + File.separator + fileName);
fos = new FileOutputStream(file);
fos.write(getData);
} finally {
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
2024-03-08 09:55:19 +08:00
}
}
/**
* 从网络http类型Url中下载文件
*
* @param urlStr
* @param fileName
* @param savePath
* @throws IOException
*/
public static void downLoadFromUrlHttp(String urlStr, String fileName,
String savePath) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.connect();
// 得到输入流
InputStream inputStream = conn.getInputStream();
byte[] getData = readInputStream(inputStream);
// 文件保存位置
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdirs();
}
// 输出流
File file = new File(saveDir + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if (fos != null) {
fos.close();
}
if (inputStream != null) {
inputStream.close();
}
}
/**
* 从输入流中获取字节数组
*
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream)
throws IOException {
2024-04-13 10:15:55 +08:00
byte[] b = new byte[102400];
2024-03-08 09:55:19 +08:00
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
2024-04-13 10:15:55 +08:00
while ((len = inputStream.read(b, 0, b.length)) != -1) {
2024-03-08 09:55:19 +08:00
bos.write(b, 0, len);
}
bos.close();
return bos.toByteArray();
}
public static void main(String[] args) {
String name = "C:/Users/solexit06/Desktop/test/";
String urls = "https://116.205.128.251:6113/pic?7db681653a5do-5el*31-25976b8-98c2cabbf**b11===sp**812=9t0470280244=7l0*4010=6ob*521e-7pi114o=2dcb2=15a&AccessKeyId=FOZAuZC0Dc84QjvL&Expires=1709893202&Signature=lJnNS138ZVoPwOar6T4QROyg590=";
try {
downLoadFromUrlHttps(urls, "1.png", name);
} catch (Exception e) {
log.error("error", e);
2024-03-08 09:55:19 +08:00
}
}
/*
* 里面的方法都是空的当方法为空是默认为所有的链接都为安全也就是所有的链接都能够访问到 当然这样有一定的安全风险可以根据实际需要写入内容
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
/***
* 校验https网址是否安全
*
* @author solexit06
*
*/
public class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
// 直接返回true:默认所有https请求都是安全的
return true;
2024-03-08 09:55:19 +08:00
}
}
}