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;
        }
    }
}
相关推荐
神仙别闹30 分钟前
基于C语言实现的(控制台)校园导航系统
java·服务器·c语言
路在脚下@32 分钟前
Spring MVC
java·spring
J不A秃V头A39 分钟前
IntelliJ IDEA 中,自动删除无用导包
java·intellij-idea
小_太_阳40 分钟前
idea_卸载与安装
java·ide·intellij-idea
旧故新长41 分钟前
版本控制和idea简体中文教程
java·开发语言·intellij-idea
疯一样的码农42 分钟前
使用 Maven 构建一个简单的 Java 项目
java·开发语言·maven
小_太_阳1 小时前
idea_常用设置
java·ide·intellij-idea
等什么君!1 小时前
Servlet细节
java·servlet
G丶AEOM2 小时前
Redis与MySQL如何保证数据一致性
java·redis
北漂编程小王子2 小时前
maven <scope>compile</scope>作用
java·maven·compile标签作用