编程语言
首页 > 编程语言> > Java模拟Form表单提交带文件调用接口

Java模拟Form表单提交带文件调用接口

作者:互联网

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestDemo1 {
    //boundary 的值随机即可
    static String boundary = "----WebKitFormBoundaryeIAzkhBx5AozTHAY";
    static String prefix = "--";
    static String newLine = "\r\n";


    public static void main(String[] args) {
        test();
    }

    private static void test() {
        try {
            URL url = new URL("http://localhost:8090");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(60000);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
            connection.setRequestProperty("Charsert", "UTF-8");
            connection.setRequestProperty("Content-type", "multipart/form-data;boundary=" + boundary);
            connection.connect();
            ConfigHttpMultipart(connection.getOutputStream());
            InputStream ins = connection.getInputStream();
            byte[] b = readBuffer(ins);
            System.out.println(new String(b,"UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void ConfigHttpMultipart(final OutputStream out) throws Exception{
        StringBuffer params = new StringBuffer();
        Map<String, String> textMap = initTextMap();
        for (Map.Entry<String, String> map : textMap.entrySet()) {
            // 注意换行符或--不要太多,太多导致数据无法传输
            params.append(newLine + prefix + boundary + newLine);
            params.append("Content-Disposition: form-data; name=\"" + map.getKey() + "\"");
            params.append(newLine + newLine);
            params.append(map.getValue());
        }
        // 隔开文本与文件
        params.append(newLine);
        out.write(params.toString().getBytes("UTF-8"));

        List<String> fileList = initFileList();
        for(int i = 0; i < fileList.size(); i++){
            //添加参数file
            File file = new File(fileList.get(i));
            StringBuffer sb = new StringBuffer();
            sb.append(newLine + prefix + boundary + newLine);
            sb.append("Content-Disposition: form-data; name=\"files\"; filename=\"" + file.getName() + "\"");
            sb.append(newLine);
            sb.append("Content-Type: multipart/form-data; boundary=" + boundary);
            sb.append(newLine + newLine);
            out.write(sb.toString().getBytes("utf-8"));

            InputStream in = new FileInputStream(file);
            byte b[] = new byte[1024];
            int len = 0;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.write(prefix.getBytes());
            in.close();
        }
        byte[] end_data = (newLine + prefix + boundary + prefix + newLine).getBytes();
        out.write(end_data);

        out.flush();
        out.close();
    }

    private static List<String> initFileList() {
        List<String> list = new ArrayList<String>();
        list.add("F:\\工作\\2021-07\\ToExcel.xlsx");
        list.add("F:\\工作\\2021-07\\print.xlsx");
        return list;
    }

    private static Map<String, String> initTextMap() {
        Map<String, String> param = new HashMap<String, String>();
        param.put("userAccount", "ceshi");
        return param;
    }

    public static byte[] readBuffer(final InputStream ins) throws IOException {
        byte b[] = new byte[1024];
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        int len = 0;
        while ((len = ins.read(b)) != -1) {
            stream.write(b, 0, len);
        }
        return stream.toByteArray();
    }

}

标签:Java,Form,newLine,表单,connection,static,new,append,out
来源: https://www.cnblogs.com/kanie-life/p/15107232.html