HttpClient发送MultipartFile多文件及多参数请求

HttpClient发送MultipartFile多文件及多参数请求

  • https://blog.csdn.net/fraya1234/article/details/134524193

httpmime

1、环境准备:

    <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>

MultipartEntityBuilder

2、Java中发送httpClient请求:

/**
     * HttpClient post multipart/form-data数据实现多文件上传
     * @param url
     * @param headers 头部参数
     * @param body body参数,json字符串
     * @param multipartFiles 文件列表
     * @param fileParName 接收的文件名
     * @return
     */
    public static String sendFilePost(String url, Map<String, String> headers, String body,List<MultipartFile> multipartFiles,String fileParName) {
        //客户端
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //请求
        HttpPost httppost = new HttpPost(url);
        
        //文件请求
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //必须设置头
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
        
        //单个文件
        String fileName = null;
        MultipartFile multipartFile = null;
        for (int i = 0; i < multipartFiles.size(); i++) {
            //第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了
            //第三个参数是文件名
            //3)
            multipartFile = multipartFiles.get(i);
            //文件名
            fileName = multipartFile.getOriginalFilename();
            InputStream inputStream = null;
            try {
                //得到流
                inputStream = multipartFile.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //添加到 请求体中。注意这个参数名:fileParName,应该为file
            builder.addBinaryBody(fileParName,inputStream, ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
        }
        //4)构建请求参数 普通表单项
		/*	StringBody stringBody = new StringBody("12", ContentType.MULTIPART_FORM_DATA);
			builder.addPart("id", stringBody);*/
        //决中文乱码
        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, Consts.UTF_8);
        //添加请求的其他参数信息
        builder.addTextBody("paramStr", body, contentType);
        //构建出 entity
        HttpEntity entity = builder.build();
        //header头
        if (null!=headers&&headers.size()>0){
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httppost.addHeader(entry.getKey(),entry.getValue());
            }
        }
        //设置上实体
        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            //进行请求
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            logger.error("请求出错:" + url, e);
            return null;
        }
        String result = null;
        try {
            if(response!=null){
                HttpEntity httpEntity = response.getEntity();
                //判断http的状态
                if (httpEntity != null && response.getStatusLine().getStatusCode()== HttpURLConnection.HTTP_OK) {// 判断请求状态
                    //转成String返回
                    result = EntityUtils.toString(httpEntity);
                }
            }
        } catch (Exception e) {
            logger.error("请求出错:" + url, e);
        } finally {
            try {
                if(response!=null){
                    response.close();
                }
            } catch (IOException e) {
                logger.error("请求出错:" + url, e);
            }
        }
        logger.info("请求的URL:" + url + ", 返回结果:" + result);
        return result;
    }
3、后端服务restful接口接参:

    @Operation(summary = "获取附件")
    @PostMapping("/xxx") //参数是文件数组
    private void sendfilepost(@RequestParam(value = "file") List<MultipartFile> mulFiles,@RequestParam(value = "paramStr") String json){
        /**这里处理自己的逻辑*/
    }

4、模拟2中调用

/**将普通文件转成MultipartFile文件*/
public static MultipartFile getMultipartFile(File file) {
    	//创建FileItem
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
    
    	//创建输入流
        try (InputStream input = new FileInputStream(file);
             //获取 item 的输出流
             OutputStream os = item.getOutputStream()) {
            // 流转移。从文件对象 转到 os中
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }
    
 		//创建消费者 文件请求
        return new CommonsMultipartFile(item);
}
 
 
public static void main(String[] args) {
    String url = "请求的服务路径";
    File f = new File("D:\\test");
    //获取下面的所有文件
    File[] files = f.listFiles();
    //创建请求参数列表
    List<MultipartFile> multiFiles = new ArrayList();
    //添加到列表中
    for(File tempFile:files){
       MultipartFile cMultiFile = getMultipartFile(tempFile);
       multiFiles.add(cMultiFile);
    }
    //批量请求
    String restr = sendFilePost(url, null, JSON.toJSONString(paramMap),multiFiles,"file");
}

————————————————

                        版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/fraya1234/article/details/134524193

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java使用HttpClient发送MultipartFile的示例代码: ```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.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; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; public class HttpClientUtil { public static String sendMultipartFile(String url, MultipartFile file, String paramStr) throws IOException { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(url); // 构建请求参数 FileBody fileBody = new FileBody(convert(file)); StringBody stringBody = new StringBody(paramStr, ContentType.create("text/plain", Charset.forName("UTF-8"))); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("file", fileBody) .addPart("paramStr", stringBody) .build(); httpPost.setEntity(reqEntity); // 发送请求 HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); String result = EntityUtils.toString(resEntity, Charset.forName("UTF-8")); return result; } private static File convert(MultipartFile file) throws IOException { File convFile = new File(file.getOriginalFilename()); file.transferTo(convFile); return convFile; } } ``` 其中,`sendMultipartFile`方法接收三个参数请求URL、MultipartFile文件请求参数。该方法使用HttpClient发送POST请求,将文件参数一起发送到指定的URL,并返回响应结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值