最近在对接外部接口时遇到返回的图片所在的服务器全都没有ssl证书,导致在前端直接用img标签展示时图片开裂。于是转为通过后端获取,绕过ssl验证之后转为base64返回。记录一下代码段。
java
package com.sy.ai.common.utils;
import cn.hutool.core.codec.Base64Encoder;
import lombok.extern.slf4j.Slf4j;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
@Slf4j
public class ImageUtil {
public static String imageUrlToBase64(String imgUrl){
URL url = null;
InputStream is = null;
ByteArrayOutputStream outStream = null;
HttpURLConnection httpUrl = null;
try {
// 忽略ssl
trustAllHttpsCertificates();
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
url = new URL(imgUrl);
httpUrl =(HttpURLConnection) url.openConnection();
// 连接超时
httpUrl.setConnectTimeout(10000);
// 读取超时、服务器响应慢
httpUrl.setReadTimeout(10000);
httpUrl.connect();
is = httpUrl.getInputStream();
outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer)) != -1){
outStream.write(buffer,0, len);
}
return "data:image/png;base64," + encode(outStream.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String encode(byte[] image) {
return Base64Encoder.encode(image);
}
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
}