【问题标题】:400 Bad Request with spring RESTSpring REST 的 400 错误请求
【发布时间】:2016-10-19 18:42:09
【问题描述】:

我有这样的春假服务

@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 文本。但是当我试图从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 错误请求错误。无法弄清楚这段代码有什么问题......

【问题讨论】:

标签: java spring rest


【解决方案1】:

像这样设置你的文件。

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

或者像这样

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

【讨论】:

  • 非常感谢。有用!! :)
猜你喜欢
  • 1970-01-01
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多