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

     开发过程中,接入第三方系统的时候,对方要求在文件上传的时候按照form表单的形式使用post请求提交,一开始使用httppost的方式,但是对方一直接收不到数据,而且是全空。当然在这之前我用postman模拟请求是好使的,于是对方给我的建议就是去看postman请求后的code,向下面图片一样的东西。

内心是各种不满,无奈还是要按照人家的来,于是开始各种搜索。万幸,找到了可以用的资源。而且代码支持多多文件上传,相当于是整个组装了form表单,暂且欣赏下面的代码吧:

    //向外发送http请求
    public String sendHttpPostRequest(String serverUrl, String[] filePaths, Map<String, String> formText) throws Exception {
        
        String BOUNDARY = "----------" + System.currentTimeMillis();
        // 向服务器发送post请求
        URL url = null;
        try {
            url = new URL(serverUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
 
        // 发送POST请求头信息
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        try {
            connection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Charset", "UTF-8");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
 
        StringBuilder message = new StringBuilder();//存放请求信息
        // 链接服务器获得输出流
        try (OutputStream out = new DataOutputStream(connection.getOutputStream())) {
            // 第一部分:传递文本表单
            for (String key : formText.keySet()) {
                message.append("--").append(BOUNDARY).append("\r\n").append("Content-Disposition: form-data; name=\"")
                        .append(key + "\"").append("\r\n").append("\r\n").append(formText.get(key)).append("\r\n");
            }
            // 写入文本表单信息
            String boundaryMessage1 = message.toString();
            out.write(boundaryMessage1.getBytes("utf-8"));
         // 第二部分: 循环读取上传文件读取个文件
            for (int i = 0; i < filePaths.length; i++) {
                File file = new File(filePaths[i]);
                if (!file.exists()) {
                    System.out.println("文件不存在或路径错误!");
                    throw new Exception("文件不存在或路径错误!");
                }
                message.delete(0, message.length());
                message.append("--");
                message.append(BOUNDARY);
                message.append("\r\n");
                System.out.println("file.getName():"+file.getName());
                message.append("Content-Disposition: form-data;name=\"order_file\";filename=\"" + file.getName() + "\"\r\n");
                message.append("Content-Type:application/octet-stream\r\n\r\n");//
                byte[] head = message.toString().getBytes("utf-8");
 
                // 输出文件表头
                out.write(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 = in.read(bufferOut)) != -1) {
                        length+=bytes;
                        for(int j = 0;j<bytes;j++){
                            System.out.print(bufferOut[j]+" ");
                        }
                        out.write(bufferOut, 0, bytes);
                    }
                    
                    System.out.println("Writelength:"+length);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 写入两个文件之间得分隔符,如果没有两个文件内容会被写在一个文件中
                /*out.write("\r\n".getBytes("utf-8"));*/
            }
            // 结尾部分
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
            out.write(foot);
            out.flush();
        } catch (IOException e1) {
            e1.printStackTrace();
            return e1.getMessage();
        }
        // 4. 从服务器获得回答的内容
        String strLine = "";
        String strResponse = "";
        try (InputStream responseIO = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(responseIO));) {
 
            while ((strLine = reader.readLine()) != null) {
                strResponse += strLine + "\n";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return strResponse;
    }

代码挺长的,可见需要拼凑的东西挺多的。

上边拼凑的是heaser的内容,其中BOUNDARY取的是当前系统时间。

整个下来,组装了最上边图片里的内容,这样发送之后,对方能够收到内容了,非常感谢博主,附上链接:

https://blog.csdn.net/qq_36380429/article/details/79267854  非常感谢

这中间除了一点问题,就是要计算文件的MD5值,我本地计算的和在线计算的文件的MD5值是一致的,但是上传之后一直返回MD5值计算错误,于是我把本地的文件传给了对方,拿到以后调用他本地函数计算结果和我也是一致的,于是判定肯定是文件传输过程中出了差错。果然,我计算的本地文件的大小是163,而对方接收到的是165,开始查!!,代码中出现了下面这个

原因是代码支持多文件上传,文件之间使用\r\n分隔,但我的是单文件上传,所以多写了两字节,注释掉以后,不再报错了。算是保留下来,以后搜索起来不用太麻烦,在遇到这样的需求可以拿过来用,不再造轮子,哈哈哈。再次感谢博主!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值