带有spring REST的400 Bad Request

时间:2016-10-19 09:19:23

标签: java spring rest

我有这样的春假休息服务

@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);
 }

当我从 http 表单中调用它时,它可以正常工作并返回 json text 。但是当我试图从java代码中调用它时

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

然后我收到 400 Bad request error 。无法弄清楚这段代码有什么问题...

1 个答案:

答案 0 :(得分:1)

像这样设置文件。

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

或者像这样

<domain xmlns:c="http://example.com/ns/core" xmlns="http://example.com/ns/core">
  <c:id>http://example.com/xyz/no-data</c:id>
</domain>