HttpClient post请求multipart/form-data类型 服务器接口入参为null

Java项目

依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.14</version>
</dependency>

请求方法:

public static String doPostFormData(String apiUrl, Map<String, Object> paramMap) {
        HttpPost httpPost = new HttpPost(apiUrl);
        httpPost.setHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);
        // 文件流参数配置
        if (MapUtils.isNotEmpty(paramMap)) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(StandardCharsets.UTF_8);
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
                Object value = entry.getValue();
                System.err.println(entry.getKey());
                if (value instanceof File) {
                    // 文件流
                    FileBody fileBody = new FileBody((File) value, ContentType.DEFAULT_BINARY);
                    builder.addPart(entry.getKey(), fileBody);
                } else {
                    StringBody stringBody = new StringBody(value.toString(), ContentType.TEXT_PLAIN);
                    builder.addPart(entry.getKey(), stringBody);
                }

            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
        }

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(120000)
                .setConnectionRequestTimeout(120000)
                .setSocketTimeout(120000)
                .build();
        httpPost.setConfig(requestConfig);

        HttpResponse response = null;
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String result = null;
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                try {
                    result = EntityUtils.toString(responseEntity);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return result;
    }

这个方法post请求到服务器会产生入参为 null 的情况

解决方案

删除

httpPost.setHeader("Content-Type", MediaType.MULTIPART_FORM_DATA);

这行 Content-Type 请求头配置。之所以不用设置请求头类型是因为

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

MultipartEntityBuilder 会自动构建请求体,不需要自己再手动设置。如果一定要自己手动设置 Content-Type 的话那就得同时把 boundary 也手动设置好,例如:

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setBoundary("----------------" + System.currentTimeMillis());
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
对于Java中的HTTPClient请求multipart/form-data,你可以使用Apache HttpClient库来实现。下面是一个简单的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.HttpClients; import java.io.File; import java.io.IOException; public class MultipartFormDataExample { public static void main(String[] args) { HttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/upload"); // 创建一个多部分实体构建器 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 添加文本参数 builder.addTextBody("username", "John Doe"); // 添加文件参数 File file = new File("path/to/image.jpg"); builder.addBinaryBody("image", file, ContentType.APPLICATION_OCTET_STREAM, file.getName()); // 构建多部分实体 HttpEntity multipartEntity = builder.build(); // 将多部分实体设置为请求的实体 httpPost.setEntity(multipartEntity); try { // 执行请求 HttpResponse response = httpClient.execute(httpPost); // 处理响应 // ... } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述代码中,我们使用了Apache HttpClient库来进行HTTP请求。首先,我们创建一个`HttpClient`实例,并指定要进行POST请求的URL。然后,我们创建一个`MultipartEntityBuilder`实例,用于构建多部分实体。我们可以使用`addTextBody`方法添加文本参数,使用`addBinaryBody`方法添加文件参数。最后,我们通过调用`build`方法构建多部分实体,并将其设置为POST请求的实体。最后,我们执行请求并处理响应。 希望以上的示例代码能对你有所帮助。<span class="em">1</span> #### 引用[.reference_title] - *1* [c#实现HttpClient拼接multipart/form-data形式参数post提交数据](https://download.csdn.net/download/kgo00/12091747)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值