public String upload() {
//HttpHeaders httpHeaders = RestTemplateUtils.basicAuthenticationInfo(poAuthConfig.getUsername(), poAuthConfig.getPassword());
//上传的地址
String url = "请求接口地址";
String filePath = "文件路径地址";
RestTemplate rest = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders() {
{
String auth = "用户admin" + ":" + "密码123456";
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String(encodedAuth);
set("Authorization", authHeader);
set("Content-Type", "multipart/form-data");
}
};
FileSystemResource resource = new FileSystemResource(new File(filePath));
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
//MultipartFile的名称
param.add("file", resource);
param.add("name", "test_template");
param.add("fileName", "test_template.xlsx");
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, httpHeaders);
ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);
String result = responseEntity.getBody();
System.out.println(result);
return result;
}
Java模拟formdata发送请求-文件上传
于 2021-07-21 19:40:18 首次发布