文章正文

java 通过HTTPS URL文件

【文档】2020-04-23

简介java 通过HTTPS URL下载文件


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import org.ueditor.exception.UeditorException;
import org.ueditor.util.X509TrustUtiil;

import com.baidu.ueditor.define.MIMEType;

public class Dowload {
    public static void downImg(String urlStr, String fileLocal) {
        try {
            // 截取图片url,去掉参数
            if (urlStr.indexOf("?") > 0) {
                urlStr = urlStr.substring(0, urlStr.indexOf("?"));
            }

            InputStream inStream = null;
            String suffix = null;
            if (urlStr.startsWith("https://")) {
                SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
                sslcontext.init(null, new TrustManager[] { new X509TrustUtiil() }, new java.security.SecureRandom());
                URL url = new URL(urlStr);
                HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
                    public boolean verify(String s, SSLSession sslsession) {
                        System.out.println("WARNING: Hostname is not matched for cert.");
                        return true;
                    }
                };
                HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
                HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());

                HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
                connection.setConnectTimeout(6000);
                connection.setReadTimeout(6000);

                int code = connection.getResponseCode();
                if (code != HttpURLConnection.HTTP_OK) {
                    throw new UeditorException("文件读取失败");
                }
                //
                System.out.println("imgUrl: " + urlStr);
                System.out.println("connectionType: " + connection.getContentType());
                suffix = MIMEType.getSuffix(connection.getContentType());
                inStream = connection.getInputStream();
            } else {
                URL url = new URL(urlStr);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                connection.setInstanceFollowRedirects(true);
                connection.setUseCaches(true);

                int code = connection.getResponseCode();
                if (code != HttpURLConnection.HTTP_OK) {
                    throw new UeditorException("文件读取失败");
                }
                //
                System.out.println("imgUrl: " + urlStr);
                System.out.println("connectionType: " + connection.getContentType());
                suffix = MIMEType.getSuffix(connection.getContentType());
                inStream = connection.getInputStream();
            }

            // 读文件流
            DataInputStream in = new DataInputStream(inStream);
            DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
            byte[] buffer = new byte[2048];
            int count = 0;
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            System.out.println("download failed");
        }
    }

    public static void main(String[] args) {
        String urlStr = "http://redisbook.readthedocs.io/en/latest/_images/graphviz-58f7b1f1f52b28f59291d194555fc9f4b1462a4c.svg";
        urlStr = "https://img0.tuicool.com/uUJVjqQ.jpg!web";
        urlStr = "http://cdn.layui.com/upload/2018_1/6167784_1515637044884_75870.png";
        urlStr = "http://redisbook.readthedocs.io/en/latest/_images/graphviz-58f7b1f1f52b28f59291d194555fc9f4b1462a4c.svg";
        String fileLocal = "d:\test.png";
        downImg(urlStr, fileLocal);
    }
}

工具类

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class X509TrustUtiil implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        // TODO Auto-generated method stub

    }
    @Override
    public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        // TODO Auto-generated method stub

    }
    @Override
    public X509Certificate[] getAcceptedIssuers() {
        // TODO Auto-generated method stub
        return null;
    }
}

打赏支持

感谢您的支持,加油!

打开微信扫码打赏,你说多少就多少

找书费时,联系客服快速获取!

扫码支持

在线客服8:30-22:30,若离线请留言!

获取教程,请联系在线客服!

扫码支持

在线客服8:30-22:30,若离线请留言!

热门阅读

找PDF电子书,太费时间?

  • 微信扫描二维码,让客服快速查找。
  • 在线客服8:30-22:00,若离线请留言!