HttpURLConnection 实战Get/Post 请求并且保存PDF文件

4 篇文章 0 订阅
2 篇文章 0 订阅
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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值