JRavil JRavil - 1 month ago 31
reST (reStructuredText) Question

400 Bad Request with spring REST

I have spring rest service such this

@RequestMapping(method = RequestMethod.POST,
path = "/getdata", consumes = {"multipart/form-data"}, produces = MediaType.APPLICATION_JSON)
public
@ResponseBody
Result getBarcode(@RequestParam("text") String sl,
@RequestParam("imageFile") MultipartFile file) {
... some logic
return new Result(text, message, !processingError);
}


When i call this from http form it works fine and return json text. But when i trying to call this from java code

RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("text", "123");
map.add("imageFile", new File("...path to file..."));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setAccept(MediaType.parseMediaTypes("application/json,text/html,application/xhtml+xml,application/xml"));
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
ResponseEntity<BcResult> response = restTemplate.exchange("http://localhost:8080/getdata", HttpMethod.POST, requestEntity, BcResult.class);


Then i am getting 400 Bad request error. Can`t figure out what is wrong with this code...

Answer

Set your file like this.

 map.add("imageFile", new FileSystemResource(new File("...path to file...")));

or like this

map.add("imageFile", new ClassPathResource("...path to file..."));