当前位置:   article > 正文

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

resttemplate,formdata请求

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95

4、 其他

4.1、 依赖包

		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.6</version>
		</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

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;
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/302900
推荐阅读
相关标签
  

闽ICP备14008679号