When I try to consume a RESTFul API using a Java client with REST Template Spring. We have an API to consume POST to which we want to send a file, for this it has a MultipartFile object of input parameter. The Java client has a MultipartFile as output with documentType property equal to "application / pdf", after consuming the POST API the input parameter of the MultipartFile object in its documented property changes to "application / octet-stream".
RESTFul client implementation:
public String uploadDocumentRestTemplate(String idUser, MultipartFile file) {
/* file.getContentType() = "application/pdf" */
ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
@Override
public String getFilename() {
return file.getOriginalFilename();
}
};
MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
bodyMap.add("file", fileAsResource);
bodyMap.add("idUser", idUser);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);
/* POST request to Restful API */
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<TodoTaskOrchModel> response = restTemplate.exchange("http://server.com:8080/api/upload",
HttpMethod.POST, requestEntity, String.class);
}
Implementation of the POST RESTFul API:
@RequestMapping(value = "/api/upload",
method = RequestMethod.POST,
produces = { MediaType.APPLICATION_JSON_VALUE })
public TodoTaskOrchModel uploadDocument(@RequestParam("idUser") String idUser, @RequestBody MultipartFile file) {
String contType = file.getContentType();
System.out.println("contType: " + contType);
}
Output: "contType = application / octet-stream"
When I try to upload a PDF or Word file then I should receive "application / pdf" or "application / msword", does anyone have any ideas?