简单示例:RestTemplate处理接口的调用以及与Ribbon/Feign配合使用调用微服务接口,处理Post文件上传的解决方案,其实就是将后台所需的MultipartFile,在请求ParamMap中,value类型存储为FileSystemResource。代码如下:
String url = "https://www.xxx.com";//请求地址
String filePath = "C:\video\202201211042.mp4";//本地文件
RestTemplate rest = new RestTemplate();//发起请求对象
//读取本地资源文件转换(有点类似于MultipartFile)
FileSystemResource resource = new FileSystemResource(new File(filePath));
//构建LinkedMultiValueMap模拟普通的表单提交
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("files", resource);
param.add("username", "张三");
//发起请求
String string = rest.postForObject(url, param, String.class);
详解:
//读取本地资源文件转换(有点类似于MultipartFile)
FileSystemResource resource = new FileSystemResource(new File(filePath));
//构建LinkedMultiValueMap模拟普通的表单提交
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("username", "张三");
map.add("files", resource);
Result dataSubmit = Common.postData("https://www.xxx.com", map);
//postData方法
//发送MULTIPART_FORM_DATA数据
public static Result postData(String url, Object data) throws Exception {
String body = null;
HttpHeaders headers = new HttpHeaders();
//设置请求头multipart/form-data模式
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//设置要传递的参数
HttpEntity<Object> request = new HttpEntity<>(data, headers);
try {
//不使用自定义超时设置,发送post请求
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, request, String.class);
if (postForEntity.getStatusCodeValue() != 200) {
return Result.error(postForEntity.getBody());
}
body = postForEntity.getBody();
} catch (Exception e) {
return Result.error(e.getMessage());
}
Map parse = JSONObject.parseObject(body, Map.class);
Result<Object> result = new Result<>();
BeanUtils.populate(result, parse);
return result;
}