需要有header和form表单上传文件的情况
@Resource
private RestTemplate restTemplate;
/**
* 文件上传到远端的服务器
* @return
*/
@PostMapping("/uploadFile")
@ResponseBody
public String uploadFile() {
String result = null;
try {
String accessToken = "your token";
String URL = "your url";
//设置请求
HttpHeaders headers = new HttpHeaders();
String token = YhtTokenUtil.getInstance().getYhtToken();
headers.add("your_token_key", token);
headers.add("Content-Type", "multipart/form-data");
//设置请求体,注意是LinkedMultiValueMap
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
File youFile = new File("D:\\you_path\\file.txt");
form.add("file", new FileSystemResource(youFile));
// form.add("your_form_file_key_of_httpRequest", new FileSystemResource(youFile));
//封装请求报文
HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
result = restTemplate.postForObject(URL, files, String.class);
log.debug("result is " + result);
} catch (Exception e) {
e.printStackTrace();
}
return "ok";
}