我是靠谱客的博主 爱撒娇天空,最近开发中收集的这篇文章主要介绍java后台访问第三方图片资源,过滤证书信任问题,并且返回文件流(直接访问第三方资源,需要在浏览器安装证书),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

过滤证书信任工具类:

public class SslVerifyUtil {
    public 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;
        }
    }
}

访问第三方图片url地址并获取文件流:

@SneakyThrows
@Override
public void getFileIoByImageUrl(String path, HttpServletRequest request, HttpServletResponse response) {
    /**
     *  备选方案:直接通过第三方图片的url地址获取到输入流
     *  目前采用方案:先根据url地址将文件下载,从本地路径读取输入流,读取完之后再将文件删除;
     *  这种方式接口的 响应时间 比从直接通过第三方图片的url地址获取到输入流的方式 快一些
     */
    //getInputStreamByUrl(备选方案方法);
   
    //临时目录
    String tempPath = tempFile + "xxx.jpg";
    String pictureRealUrl = 第三方图片url地址;
    //根据第三方url地址下载图片到本地临时目录
    File file1 = downloadFileService.downloadFileFromNetWork(pictureRealUrl, tempPath);
    OutputStream toClient = null;
    try {
        InputStream fis = new BufferedInputStream(new FileInputStream(tempPath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Length", "" + file1.length());
        response.setContentType("image/jpg");
        toClient= new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        if(file1 !=null){
            file1.delete();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        if(toClient !=null){
            toClient.flush();
            toClient.close();
        }
    }
}

备选方案代码:

public static InputStream getInputStreamByUrl(String strUrl) {
    HttpURLConnection conn = null;
    try {
        //过滤证书信任
        SslVerifyUtil.trustAllHttpsCertificates();
        HostnameVerifier hv = new HostnameVerifier() {
            @Override
            public boolean verify(String urlHostName, SSLSession session) {
                log.info("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                return true;
            }
        };
        URL url = new URL(strUrl);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(20 * 1000);
        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        IOUtils.copy(conn.getInputStream(), output);
        return new ByteArrayInputStream(output.toByteArray());
    } catch (Exception e) {
        log.error(e + "");
    } finally {
        try {
            if (conn != null) {
                conn.disconnect();
            }
        } catch (Exception e) {
            log.error(e + "");
        }
    }
    return null;
}

downloadFileFromNetWork方法代码:

@SneakyThrows
@Override
@Nls
public File downloadFileFromNetWork(@NotNull String imgUrl, @NotNull String localPath) {
    File file = new File(localPath);
    if(file.exists()) {
        return file;
    }
    //过滤证书信任问题
    SslVerifyUtil.trustAllHttpsCertificates();
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
                log.info("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
            return true;
        }
    };
    InputStream inputStream = downloadInsFromNetWork(imgUrl);
    if(inputStream != null) {
        FileOutputStream fos = null;
        try {
            if(!file.exists()) {
                if(!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            }
            int index;
            byte[] bytes = new byte[1024];
            fos = new FileOutputStream(file);
            while ((index = inputStream.read(bytes)) != -1) {
                fos.write(bytes, 0, index);
                fos.flush();
            }
            return file;
        } finally {
            if(fos != null) {
                fos.close();
            }
            inputStream.close();
        }

    }
    return null;
}

downloadInsFromNetWork方法代码:

public InputStream downloadInsFromNetWork(@NotNull String imgUrl) {
    URL url;
    URLConnection connection;
    try {
        url = new URL(imgUrl);
        connection = url.openConnection();
    } catch (IOException e) {
        return null;
    }
    connection.setConnectTimeout(3000);
    connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
    InputStream imgIs = null;
    try {
        imgIs = connection.getInputStream();
    } catch (IOException e) {
    }
    return imgIs;
}

最后

以上就是爱撒娇天空为你收集整理的java后台访问第三方图片资源,过滤证书信任问题,并且返回文件流(直接访问第三方资源,需要在浏览器安装证书)的全部内容,希望文章能够帮你解决java后台访问第三方图片资源,过滤证书信任问题,并且返回文件流(直接访问第三方资源,需要在浏览器安装证书)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部