java發送post請求並下載返回文件


直接上代碼

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

public class ExportPost {
    public static String url = "http://localhost:8088/file/xxx/download2";public static String cookie = "cookie";
    public static void main(String[] args) throws Exception {
        getInternetRes("D:\\demoefile",url,"a.pdf");
    }

    public static void getInternetRes(String newUrl, String oldUrl, String fileName) throws Exception {
        URL url = null;
        HttpURLConnection con = null;
        InputStream in = null;
        FileOutputStream out = null;
        try {
            url = new URL(oldUrl);
            //建立http連接,得到連接對象
            con = (HttpURLConnection) url.openConnection();
            //設置通用的請求頭屬性
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestMethod("POST");    // 默認是 GET方式
            con.setUseCaches(false);         // Post 請求不能使用緩存
            con.setInstanceFollowRedirects(true);   //設置本次連接是否自動重定向
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            con.setRequestProperty("Content-Type", "application/form-data");
//            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//            con.setRequestProperty("Content-Type","application/form-data;charset=utf-8");
            // boundary就是request頭和上傳文件內容的分隔符
            String BOUNDARY = "---------------------------123821742118716";
            con.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
            con.setRequestProperty("Connection","Keep-Alive");//設置與服務器保持連接
            con.setRequestProperty("Accept-Language", "zh-CN,zh;0.9");

            con.setRequestProperty("cookie",cookie);

            StringBuilder sb2 = new StringBuilder();
            sb2.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
            sb2.append("Content-Disposition: form-data; name=\"no\"\r\n\r\n");
            sb2.append("xxx");

            sb2.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
            sb2.append("Content-Disposition: form-data; name=\"json\"\r\n\r\n");
            sb2.append("{\"id\": \"123456\",\"mc\": \"測試名稱\"}");

            con.connect();
            OutputStream outputStream = con.getOutputStream();
            outputStream.write(sb2.toString().getBytes());
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            outputStream.write(endData);
            outputStream.flush();
            outputStream.close();

            //輸入流讀取文件
            in = con.getInputStream();
            //轉化為byte數組
            byte[] data = getByteData(in);
            //建立存儲的目錄、保存的文件名
            File file = new File(newUrl+ DateUtil.formatDate(new Date()));
            if (!file.exists()) {
                file.mkdirs();
            }
            //修改文件名   用id重命名
            File res = new File(file + File.separator + fileName);
            //寫入輸出流
            out = new FileOutputStream(res);
            out.write(data);
//            logger.info("下載 successfully!");
            System.out.println("下載 successfully!");
        } catch (IOException e) {
//            logger.error("下載出錯!"+e.toString());
            System.out.println("下載出錯!"+e.toString());
        } finally {
            //關閉流
            try {
                if (null != out){
                    out.close();
                }
                if (null != in){
                    in.close();
                }
            } catch (IOException e) {
//                logger.error("下載出錯!"+e.toString());
                System.out.println("下載出錯!"+e.toString());
            }
        }
    }

    /**
     *
     * @Title: getByteData
     * @Description: 從輸入流中獲取字節數組
     * @author zml
     * @date Sep 12, 2017 7:38:57 PM
     */
    private static byte[] getByteData(InputStream in) throws IOException {
        byte[] b = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len = 0;
        while ((len = in.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        if(null!=bos){
            bos.close();
        }
        return bos.toByteArray();
    }


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM