模拟post表单的形式提交文件,同时携带其它的参数

时间:2025-03-20 09:54:08
    //向外发送http请求
    public String sendHttpPostRequest(String serverUrl, String[] filePaths, Map<String, String> formText) throws Exception {
        
        String BOUNDARY = "----------" + ();
        // 向服务器发送post请求
        URL url = null;
        try {
            url = new URL(serverUrl);
        } catch (MalformedURLException e) {
            ();
            return ();
        }
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) ();
        } catch (IOException e) {
            ();
            return ();
        }
 
        // 发送POST请求头信息
        (true);
        (true);
        (false);
        try {
            ("POST");
        } catch (ProtocolException e) {
            ();
            return ();
        }
        ("Connection", "Keep-Alive");
        ("Charset", "UTF-8");
        ("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
 
        StringBuilder message = new StringBuilder();//存放请求信息
        // 链接服务器获得输出流
        try (OutputStream out = new DataOutputStream(())) {
            // 第一部分:传递文本表单
            for (String key : ()) {
                ("--").append(BOUNDARY).append("\r\n").append("Content-Disposition: form-data; name=\"")
                        .append(key + "\"").append("\r\n").append("\r\n").append((key)).append("\r\n");
            }
            // 写入文本表单信息
            String boundaryMessage1 = ();
            (("utf-8"));
         // 第二部分: 循环读取上传文件读取个文件
            for (int i = 0; i < ; i++) {
                File file = new File(filePaths[i]);
                if (!()) {
                    ("文件不存在或路径错误!");
                    throw new Exception("文件不存在或路径错误!");
                }
                (0, ());
                ("--");
                (BOUNDARY);
                ("\r\n");
                ("():"+());
                ("Content-Disposition: form-data;name=\"order_file\";filename=\"" + () + "\"\r\n");
                ("Content-Type:application/octet-stream\r\n\r\n");//
                byte[] head = ().getBytes("utf-8");
 
                // 输出文件表头
                (head);
                // 文件正文部分
                // 把文件已流文件的方式 推入到url中
                try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {//DataInputStream in = new DataInputStream(new FileInputStream(file))
                    int bytes = 0;
                    int length = 0;//用于测试
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = (bufferOut)) != -1) {
                        length+=bytes;
                        for(int j = 0;j<bytes;j++){
                            (bufferOut[j]+" ");
                        }
                        (bufferOut, 0, bytes);
                    }
                    
                    ("Writelength:"+length);
                } catch (IOException e) {
                    ();
                }
                // 写入两个文件之间得分隔符,如果没有两个文件内容会被写在一个文件中
                /*("\r\n".getBytes("utf-8"));*/
            }
            // 结尾部分
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
            (foot);
            ();
        } catch (IOException e1) {
            ();
            return ();
        }
        // 4. 从服务器获得回答的内容
        String strLine = "";
        String strResponse = "";
        try (InputStream responseIO = ();
                BufferedReader reader = new BufferedReader(new InputStreamReader(responseIO));) {
 
            while ((strLine = ()) != null) {
                strResponse += strLine + "\n";
            }
        } catch (IOException e) {
            ();
            return ();
        }
        return strResponse;
    }