HttpURLConnection 實戰Get/Post 請求並且儲存PDF檔案

com未來發表於2020-11-26
package com.test.pdf;

import com.test.logger.LoggerControler;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class PDFTool {
    private static final LoggerControler LOGGER = LoggerControler.getLogger(PDFTool.class);

    public static void httpGetByNotSSLAndSaveFile(String httpUrl, String fileName, String savePath) {
        BufferedReader input = null;
        StringBuilder sb = null;
        URL url = null;
        HttpURLConnection con = null;
        try {
            url = new URL(httpUrl);
            try {
                // trust all hosts
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                if (url.getProtocol().toLowerCase().equals("https")) {
                    https.setHostnameVerifier(DO_NOT_VERIFY);
                    con = https;
                } else {
                    con = (HttpURLConnection) url.openConnection();
                }
                con.setConnectTimeout(10 * 1000);
                con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
                InputStream inputStream = con.getInputStream();
                byte[] getData = readInputStream(inputStream);
                //if can not found will make it
                File saveDir = new File(savePath);
                if (!saveDir.exists()) {
                    saveDir.mkdir();
                }
                File file = new File(saveDir + File.separator + fileName);
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(getData);
                if (fos != null) {
                    fos.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                LOGGER.info(url + " download success, savePath =" + savePath);
            } catch (Exception e) {
                LOGGER.error("httpGetByNotSSLAndSaveFile() error, message=" + e.getMessage());
                e.printStackTrace();
            }
        } catch (MalformedURLException e1) {
            LOGGER.error("httpGetByNotSSLAndSaveFile() error, message=" + e1.getMessage());
            e1.printStackTrace();
        } finally {
            // close buffered
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // disconnecting releases the resources held by a connection so they may be closed or reused
            if (con != null) {
                con.disconnect();
            }
        }
    }

    public static void httpPostByNotSSLAndSaveFile(String httpUrl, String cookies, String paramBody, String fileName, String savePath) {
        BufferedReader input = null;
        HttpURLConnection con = null;
        try {
            URL url = new URL(httpUrl);
            // trust all hosts
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            if ("" != cookies) {
                https.setRequestProperty("Cookie", cookies);
            }
            https.setRequestMethod("POST");
            String[] paramList = paramBody.split("&");
            for (String paramObj : paramList) {
                String[] paramOneList = paramObj.split("=");
                https.setRequestProperty(paramOneList[0], URLEncoder.encode(paramOneList[1], "utf-8"));
            }
            if (url.getProtocol().toLowerCase().equals("https")) {
                https.setHostnameVerifier(DO_NOT_VERIFY);
                con = https;
            } else {
                con = (HttpURLConnection) url.openConnection();
            }
            con.setConnectTimeout(10 * 1000);
            con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.connect();
            DataOutputStream dataout = new DataOutputStream(con.getOutputStream());
            dataout.writeBytes(paramBody);
            dataout.flush();
            dataout.close();
            LOGGER.info("getContentLength=" + con.getContentLength());
            LOGGER.info("getResponseCode=" + con.getResponseCode());
            LOGGER.info("getContentType=" + con.getContentType());
            InputStream inputStream = con.getInputStream();
            byte[] getData = readInputStream(inputStream);
            //if can not found will make it
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            File file = new File(saveDir + File.separator + fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            LOGGER.info(url + " download success, savePath =" + savePath);
        } catch (Exception e) {
            LOGGER.error("httpGetByNotSSLAndSaveFile() error, message=" + e.getMessage());
            e.printStackTrace();
        } finally {
            // close buffered
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // disconnecting releases the resources held by a connection so they may be closed or reused
            if (con != null) {
                con.disconnect();
            }
        }
    }

    final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    /**
     * Trust every server - dont check for any certificate
     */
    private static void trustAllHosts() {
        final String TAG = "trustAllHosts";
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
                LOGGER.info(TAG + " checkClientTrusted");
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
                LOGGER.info(TAG + " checkServerTrusted");
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }
        }};
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}

相關文章