简介
本文将使用RestTemplate调用带有MultiPartFile的多文件接口,以及GET/POST请求案例
1、GET请求
/**
* GET请求 - 获取Token
*
* @return java.lang.String
*/
public String getToken() {
String token = null;
JSONObject result;
try {
String requestUrl = "xxx?client_id=" + clientId + "&client_secret=" + clientSecret;
ResponseEntity<String> entity = restTemplate.getForEntity(requestUrl, String.class);
log.info("请求返回=========={}", entity.getBody());
result = JSONObject.parseObject(entity.getBody());
if ("200".equals(result.getString("resCode"))) {
JSONObject data = JSONObject.parseObject(result.getString("data"));
token = data.getString("access_token");
} else {
log.info("请求TOKEN错误=========={}", result);
}
} catch (Exception e) {
log.error("请求TOKEN异常=========={}", e.getMessage());
}
return token;
}
2、POST请求
/**
* POS请求
*
* @param dto 传参
* @return JSONObject
*/
public JSONObject doPost(ExpenseDeleteDTO dto) {
JSONObject result;
try {
String requestUrl = "xxx";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("branch_code", dto.getBranchCode());
headers.add("user_code", dto.getUserCode());
headers.add("system_type", systemType);
headers.add("token", dto.getToken());
HttpEntity<Object> request = new HttpEntity<>(dto, headers);
ResponseEntity<String> entity = restTemplate.postForEntity(requestUrl, request, String.class);
log.info("请求返回=========={}", entity.getBody());
result = JSONObject.parseObject(entity.getBody());
} catch (Exception e) {
log.error("请求异常=========={}", e.getMessage());
}
return result;
}
3、POST请求 附带MultipartFile
/**
* POST请求
*
* @param token token
* @param files 多个文件
* @return JSONObject
*/
public JSONObject doPostUpload(String token, List<MultipartFile> files) {
JSONObject result;
try {
String requestUrl = "xxx";
HttpHeaders headers = new HttpHeaders();
// 如果是文件,使用MULTIPART_FORM_DATA
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.add("token", token);
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
for (MultipartFile file : files) {
ByteArrayResource byteArrayResource = new ByteArrayResource(file.getBytes()) {
@Override
public long contentLength() {
return file.getSize();
}
@Override
public String getFilename() {
return file.getOriginalFilename();
}
};
params.add("files", byteArrayResource);
}
// 参数和请求头放到请求体
HttpEntity<Object> request = new HttpEntity<>(params, headers);
ResponseEntity<String> entity = restTemplate.postForEntity(requestUrl, request, String.class);
log.info("请求返回=========={}", entity.getBody());
result = JSONObject.parseObject(entity.getBody());
} catch (Exception e) {
log.error("请求上传OCR发票异常=========={}", e.getMessage());
}
return result;
}