简体   繁体   中英

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...

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..."));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM