Java读取外链图片忽略ssl验证转为base64

最近在对接外部接口时遇到返回的图片所在的服务器全都没有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;
        }
    }
}
相关推荐
robin_suli11 分钟前
Spring事务的传播机制
android·java·spring
青云交13 分钟前
Java 大视界 -- Java 大数据在智能电网电力市场交易数据分析与策略制定中的关键作用(162)
java·大数据·数据分析·交易策略·智能电网·java 大数据·电力市场交易
m0Java门徒19 分钟前
Java 递归全解析:从原理到优化的实战指南
java·开发语言
云徒川28 分钟前
【设计模式】原型模式
java·设计模式·原型模式
张张张3121 小时前
4.2学习总结 Java:list系列集合
java·学习
KATA~1 小时前
解决MyBatis-Plus枚举映射错误:No enum constant问题
java·数据库·mybatis
xyliiiiiL1 小时前
一文总结常见项目排查
java·服务器·数据库
shaoing1 小时前
MySQL 错误 报错:Table ‘performance_schema.session_variables’ Doesn’t Exist
java·开发语言·数据库
腥臭腐朽的日子熠熠生辉2 小时前
解决maven失效问题(现象:maven中只有jdk的工具包,没有springboot的包)
java·spring boot·maven
ejinxian2 小时前
Spring AI Alibaba 快速开发生成式 Java AI 应用
java·人工智能·spring