【JAVA】HTTP上传多文件和其他类型参数混合传输以及对应的接收方式

1.POST请求如下

/**
 * Http 请求工具类
 * @Author: CcchenCoco
 * @Version: V1.0 HttpUtils, 2021/10/15 15:45
 **/
@Slf4j
public class HttpUtils {

    /**
     * 上传文件(多文件)
     * @Author: CcchenCoco
     * @Date: 2022/2/22 17:19
     * @Param:
     **/
    public static String postFileAndObj(String url, File[] files, Map<String, Object> requestParams) throws Exception {

        BufferedReader responseReader = null;
        OutputStream dos= null;
        String BOUNDARY = "------------------------------fbe188897ec8";

        try {
            //建立连接
            URL reqUrl = new URL(url);
            HttpURLConnection httpConn = (HttpURLConnection) reqUrl.openConnection();
            //设置参数
            httpConn.setDoOutput(true);   //需要输出
            httpConn.setDoInput(true);   //需要输入
            httpConn.setUseCaches(false);  //不允许缓存
            httpConn.setRequestMethod("POST");   //设置POST方式连接
            httpConn.setRequestProperty("Connection", "Keep-Alive");    // 设置字符编码连接参数
            httpConn.setRequestProperty("Charset", "UTF-8");    // 设置字符编码
            httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);   // 设置请求内容类型
            httpConn.setConnectTimeout(30000);
            httpConn.setReadTimeout(30000);

            //连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect
            httpConn.connect();
            //建立输入流,向指向的URL传入参数
            dos = httpConn.getOutputStream();

            StringBuffer strBuf = new StringBuffer();
            int strBufLen = 0;
            // 其他参数
            for (String key : requestParams.keySet()) {
                if (requestParams.get(key) instanceof Collection<?>) {
                    List<Object> list = (List<Object>) requestParams.get(key);
                    for (Object object : list) {
                        strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                        strBuf.append("Content-Disposition: form-data; " + "name=\" " + key + "\"\r\n\r\n");
                        strBuf.append(object.toString());
                        dos.write(strBuf.toString().getBytes());
                        // 清空 StringBuffer
                        strBufLen = strBuf.length();
                        strBuf.delete(0, strBufLen);
                    }
                } else {
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; " + "name=\" " + key + "\"\r\n\r\n");
                    strBuf.append(requestParams.get(key));
                    dos.write(strBuf.toString().getBytes());
                    // 清空 StringBuffer
                    strBufLen = strBuf.length();
                    strBuf.delete(0, strBufLen);
                }
            }

            // 文件
            for (File file : files) {
                strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                strBuf.append("Content-Disposition: form-data; " + "name=\"files\";filename=\"" + file.getName()+ "\"\r\n\r\n");
                dos.write(strBuf.toString().getBytes());
                // 清空 StringBuffer
                strBufLen = strBuf.length();
                strBuf.delete(0, strBufLen);

                // 文件数据部分
                DataInputStream in = new DataInputStream(new FileInputStream(file));
                int bytes = 0;
                byte[] bufferOut = new byte[in.available()];
                while ((bytes = in.read(bufferOut)) != -1) {
                    dos.write(bufferOut, 0, bytes);
                }
                dos.write("\r\n".getBytes());
            }

            // 结尾
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            dos.write(endData);

            dos.flush();

            //获得响应状态
            int resultCode = httpConn.getResponseCode();
            if (HttpURLConnection.HTTP_OK == resultCode) {
                StringBuffer sb = new StringBuffer();
                String readLine = new String();
                responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine);
                }

//                System.out.println(sb.toString());
                log.info(sb.toString());
//                JSONObject json = JSONObject.parseObject(sb.toString(),JSONObject.class);
                return sb.toString();
            }

        } catch (Exception e) {
            log.error("post 请求失败:" + url);
        } finally {
            if(null != responseReader) responseReader.close();
            if(null != dos) dos.close();
        }
        return null;
    }
}

2.方法应用

List<File> files = new ArrayList<>();
...... // 省略获取文件列表的业务逻辑
Map<String, Object> param = new HashMap<>();
param.put("param1", param1);
param.put("param2", param2);
param.put("param3", param3);
File[] fileArray = files.toArray(new File[files.size()]);
String json = null;
try {
    json = HttpUtils.postFileAndObj(url, fileArray, param);
} catch (Exception e) {
    log.error("post请求失败:" + url);
}

3.接收方式(Controller层)

/**
    * 多文件接收
    * @Author: CcchenCoco
    * @Date: 2022/2/23 10:07
    * @Param:
**/
@PostMapping("/receiveFiles")
public ResponseBean receiveFiles(MultipartFile[] files, String param1, String param2, String[] param3) {
    
    Map<String, Object> result = testImpl.receiveFiles(files, param1, param2, param3);

    return new ResponseBean(result);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值