我遇到报这个错是因为需要把图片取出来转为base64编码,使用freemarker导出为Word时图片位置需要将图片转为base64编码,由于图片放置与内网且保存地址是https形式的,所以就会报证书错误,这里就需要我们手动去忽略证书问题;
解决代码如下:
private static byte[] toByteArray(InputStream inputStream) throws Exception {
byte[] buffer = new byte[1024];
int len;
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
return outputStream.toByteArray();
}
}
static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@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;
}
}};
static class NullHostNameVerifier implements HostnameVerifier {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
}
/**
* 获取https图片,兼容http地址图片
*
* @param imageUrl
* @return
*/
public static String imageFromUrlByHttps(String imageUrl) {
//new一个URL对象
URL url = null;
try {
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
url = new URL(imageUrl);
//打开链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时响应时间为5秒
conn.setConnectTimeout(5 * 1000);
//通过输入流获取图片数据
InputStream inputStream = conn.getInputStream();
//将图片转为base64编码
byte[] data = toByteArray(inputStream);
inputStream.close();
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
// 直接返回图片数据流
return Base64.getEncoder().encodeToString(data);
} catch (Exception e) {
log.error("读取https地址图片失败!", e);
}
return null;
}