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();
    }


}