【nacos】RestTemplate POST请求发送form-data格式的数据

1、业务需求

发送请求给nacos托管的服务,且请求报文格式为multipart/form-data的数据。支持复杂类型的参数,包含文件类型。

2、 常用依赖包

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.58</version>
		</dependency>
		<dependency>
			<groupId>com.xiaoleilu</groupId>
			<artifactId>hutool-all</artifactId>
			<version>3.0.9</version>
		</dependency>

3、 请求方式实现


import java.io.File;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import cn.hutool.core.io.FileUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Component
public class HttpUtils {
	
	private static RestTemplate restTemplate;
	
	@Autowired
	public HttpUtils(RestTemplate restTemplate) {
		this.restTemplate = restTemplate;
	}
	
	/**
     * post请求发送form-data格式的数据
     * @param url  	请求url
     * @param param 请求参数
     * @param clazz 请求类型
     * @return
     */
    public static <V,T> T doPostFormData(String url, Map<String,Object> param,Class<T> clazz) {
        return doPostFormData(url, param,new TypeReference<T>() {
			@Override
			public Type getType() {
				return clazz;
			}
		});
    }
    
	/**
     * post请求发送form-data格式的数据
     * @param url  	请求url
     * @param param 请求参数
     * @param type 请求类型
     * @return
     */
    public static <T> T doPostFormData(String url, Map<String,Object> param,TypeReference<T> type) {
    	HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.MULTIPART_FORM_DATA);
		MultiValueMap<String,Object> body = new LinkedMultiValueMap<String, Object>();
        try {
            //表单中其他参数
           if(param != null) {
        	   for(Map.Entry<String, Object> entry: param.entrySet()) {
        		   Object value = entry.getValue();
                   if(value instanceof File) {
                	   File file = (File)value;
                	   ByteArrayResource byteArrayResource = new ByteArrayResource(FileUtil.readBytes(file)) {
                		   @Override
                		public String getFilename() {
                			return file.getName();
                		}
                	   };
                	   System.err.println(entry.getKey()+" ==>"+byteArrayResource.getByteArray().length);
                	   body.add(entry.getKey(), byteArrayResource);
                   }else {
                	   body.add(entry.getKey(), value);   
                   }
               }
           }
           
         //用HttpEntity封装整个请求报文
           HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
         // 执行POST请求
    		ResponseEntity<String> res = restTemplate.postForEntity(url, entity, String.class);// 执行提交
    		log.info("res:{}",res.getBody());
    		return JSON.parseObject(res.getBody()).toJavaObject(type);
        } catch (Exception e) {
            log.error("调用HttpPost失败!" ,e);
        } 
        return null;
    }
}

4、 其他

4.1、 依赖包

		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.6</version>
		</dependency>

4.2、 文件工具包实现逻辑

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FileUtil {
	/**
	 * MultipartFile对象转换File对象
	 * @param 存储文件路径,包含文件名
	 * @param multipartFile 文件操作对象
	 */
	public static File getFile(String path,MultipartFile multipartFile) {
		try {
			File file = new File(path); 
			FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
			return file;
		} catch (IOException e) {
			log.error("",e);
		}
		return null;
	}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值