HttpClient方式请求发送multipart-form-data混合数据(包括多个文件和json字符串等)

前言:

之前用了spring框架的restTemplate实现multipart-form-data混合数据(包括多个文件和json字符串等)的上传,现在使用httpClient方式来实现。

环境:

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5.3</version>
</dependency>

实现:

发送端:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public static void main(String[] args) {
    List<String> filePaths = new ArrayList<>();
    filePaths.add("E:\\test\\picture\\大.png");
    filePaths.add("E:\\test\\picture\\2.png");
    sendMultiFormMixData("http://localhost:8080/receive", filePaths, "测试多文件数据中文乱码");
}
 
   public static void sendMultiFormMixData(String url, List<String> filePaths, String data) {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);

        try {
            // 设置传输参数,设置编码。设置浏览器兼容模式,解决文件名乱码问题
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            for (String filePath : filePaths) {
                File file = new File(filePath);
                if (!file.exists()) {
                    continue;
                } else {
//                    // 无法解决中文文件名?的问题
//                    ContentType contentType = ContentType.create("multipart/form-data", Charset.forName("UTF-8"));
//                    ContentBody fileBody = new FileBody(file, contentType);
                    ContentBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);
                    builder.addPart("file", fileBody);
                }
            }
            // 解决中文字符?的问题
            ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
            builder.addPart("data", new StringBody(data, contentType));
            HttpEntity httpEntity = builder.build();
            httpPost.setEntity(httpEntity);
            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String jsonData = EntityUtils.toString(response.getEntity(),  "UTF-8");
                System.out.println("response result = " + jsonData);
            } else {
                System.out.println("no response");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

接收端:

@PostMapping(value = "/receive")
public Object testUploading(@RequestParam("file") MultipartFile[] files , String data) {
    String filepath = "E:\\test\\save\\";
    File targetFile = new File(filepath);
    if (!targetFile.exists()) {
        targetFile.mkdirs();
    }
    List<String> dp = new ArrayList<>() ;
    for(int i = 0 ; i < files.length ; i++){
        MultipartFile file = files[i] ;
        try {
            FileOutputStream out = new FileOutputStream(filepath + file.getOriginalFilename());
            out.write(file.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return "SUCCESS";
}

总结:

1、httpClient工具类在平常的工作中使用还是比较广泛的,一般网上都到的对其封装的工具类都是比较好的,除了一些特殊的要求需要自己查看资料编写一下,问题不大;
2、注意导包的问题以及一些api过时,既然有新的,代码上尽量还是用新的。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值