HttpPost请求Content-Type:multipart/form报错org.springframework.web.multipart.MultipartException

问题:

​ 最近需要通过Post请求通过表单形式(Content-Type:multipart/form-data)传递文本数据,但是调用其他服务接口的时候,使用PostMan调用一切正常,但是使用Java代码的httpclient包的HttpPost请求该接口时报错:

{"timestamp":1681893336914,"status":500,"error":"Internal Server Error","exception":"org.springframework.web.multipart.MultipartException","message":"Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found","path":"/xxx"}

​ 从字面意思来看是找不到分隔符“boundary”而报错了。

分析:

​ 通过抓包来看,postman请求的时候会自动在Content-Type后面并接一个随机生成的boundary(“boundary= xxxxx”),然后再对请求体进行一个分隔符包装。

  • 截图:
    • 请求头Conten—type:

      在这里插入图片描述

    • 请求体文本:

      在这里插入图片描述

    • postman自动生成“boundary”的地方

      在这里插入图片描述

要解决这个问题就要解决:

如何使用HttpPost请求自动生成“boundary”放到请求头Conten-Type并用该“boundary”包装请求体呢?

解决:

核心代码:

			HttpPost httpPost = new HttpPost(url);    		
			//boundary分隔符随机生成
            String boundary = UUIDGenerator.generateUUIDWithOutSlash();
			//【核心】这里boundary=别忘了!!!!!!!
            httpPost.addHeader(HTTP.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
            log.info("请求 openapi  Authorization:{}", headerAuth);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                	//【核心】这里别忘了设置!!!!
                    .setBoundary(boundary);
            if (!CollectionUtils.isEmpty(param)) {
                //设置请求体参数
                for (String item : param.keySet()) {
                    //添加文本类容,如果要发送文件就使用 builder.addBinaryBody
                    builder.addTextBody(item,param.get(item));
                }
            }
            //构建请求实体
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);

MultipartEntityBuilder这个类如果无法引入请引入如下jar包,版本号和httpclient保持一致即可:

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
        </dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码码哈哈0.0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值