package com.jianshui.invoice.utils;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Description
 * @Author 巩权林
 * @Date 2022-09-20 10:42
 **/
public class DownPdfTest {

    /**
     * pdf 下载案例
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        String fileName = "test";//文件名带格式
        String filePath = "C:\\temp\\";
        String utlFilepath = "http://localhost:8080/file/query/eyJjb250ZW50VHlwZSI6InBkZiIsInNlcnZpY2VQcm92aWRlciI6ImNvcyIsInN0b3JhZ2VQYXRoIjoiMGI2MWU1MGI3NWUyNGZhZTk2NDk3NjljMjU2MjE3NTYifQ==";
        HttpURLConnection conn = null;
        String contentType = "pdf";
        do {
            URL url = new URL(utlFilepath);
            conn = (HttpURLConnection) url.openConnection();
            conn.setInstanceFollowRedirects(false);
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setInstanceFollowRedirects(false);
            if (conn.getResponseCode() == 302) {
                contentType = conn.getHeaderField("content-type");
                if (contentType.indexOf("pdf") != -1) {
                    fileName += ".pdf";
                } else {
                    fileName += ".ofd";
                }
                //如果会重定向，保存302重定向地址，以及Cookies,然后重新发送请求(模拟请求)
                String location = conn.getHeaderField("Location");
                conn.disconnect();
                utlFilepath = location;
                conn = (HttpURLConnection) new URL(utlFilepath).openConnection();
                conn.setConnectTimeout(15000);
                conn.setReadTimeout(15000);
            }
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK)
                break;
        } while (true);

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        File file = new File(filePath + fileName);
        file.createNewFile();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath + fileName));
        try {
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = inputStream.read(bufferOut)) != -1) {
                bos.write(bufferOut, 0, bytes);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            inputStream.close();
            bos.close();
        }
    }
}
