欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringCloud接收MultiPartFile文件 | HttpClient发送MultiPartFile请求到SpringCloud

程序员文章站 2022-06-26 08:03:36
...

首先,感谢作者 一缕82年的清风的文章,因为在使用HttpClient发送请求之前,我使用@requestPart注解,或者通过在@FeignClient中配置configuration都不行。接下来详细说说通过HttpClient发送请求的做法。

 

本地环境:eclipse+springboot+springcloud

本例使用的maven依赖:

!-- HttpClient -->
	    <dependency>
	        <groupId>commons-httpclient</groupId>
	        <artifactId>commons-httpclient</artifactId>
	        <version>3.1</version>
	        <type>pom</type>
	    </dependency>

1.新建HttpUtils工具类,内容如下:

package com.aspire.oms.util;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

/**
* @author rbrother
* @version 创建时间:2019年9月4日 下午10:35:37
* 类说明
*/

public class HttpUtils {
	
	/**
     * 使用httpclint 发送文件
     * @author: qingfeng
     * @date: 2019-05-27
     * @param url --> SpringCloud 对应方法的 @RequestMapping 内的映射地址
     * @file --> 上传的文件
     * @fileParamName --> SpringCloud 对应方法中的接收参数名,例如 void method(@RequestParam("file")MultiPartFIle file) ;中@RequestParam内的value值
     * @headParam --> http请求头信息
     * @otherParam 除了上传文件,有时候还要上传别的参数,把这些请求参数存入这个映射中
     * @return 响应结果
     */
    public static String uploadFile(String url ,MultipartFile file,String fileParamName,Map<String,String>headerParams,Map<String,String>otherParams) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            String fileName = file.getOriginalFilename();
            HttpPost httpPost = new HttpPost(url);
            //添加header
            for (Map.Entry<String, String> e : headerParams.entrySet()) {
                httpPost.addHeader(e.getKey(), e.getValue());
            }
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("utf-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
            builder.addBinaryBody(fileParamName, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
            for (Map.Entry<String, String> e : otherParams.entrySet()) {
                builder.addTextBody(e.getKey(), e.getValue());// 类似浏览器表单提交,对应input的name和value
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    
}

要注意,这种情况下,一旦对方返回的结果中存在中文有可能出现乱码,解决方法就是向上面的代码中加入:

builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题、

2.本地SpringBoot对应请求方法内容

/**
	 * 
	 * @param file 文件
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "test", method = RequestMethod.POST)
	public ServerResponse test(
			@RequestParam("file") MultipartFile file, @RequestParam("param1") String param1,
			@RequestParam("param2") String param2, @RequestParam("param3") String param3
			){
		
		String result = "" ;
		try {
			if(file != null) {
				String url = hostName + "springcloud中的@RequestMapping的value" ;
				String fileParamName = "file" ;
				Map<String, String> headerParams = new HashMap<>() ;
				Map<String, String> otherParams = new HashMap<>() ;
				otherParams.put("param1", param1) ;
				otherParams.put("param2", param2) ;
                otherParams.put("param3", param3) ;
				result = HttpUtils.uploadFile(url, file, fileParamName, headerParams, otherParams) ;
				System.out.println(result);
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}

3.SpringCloud接收方法:

 @RequestMapping(value = "/springcloud中的@RequestMapping的value", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    public ServerResponse testResponse(@RequestParam("param1") String param1, @RequestParam("param2") String param2, @RequestParam("param3") String param3, @RequestParam("file") MultipartFile file) {
    //自己的判断逻辑        
}