400错误请求,RESTTEMPLATE

时间:2017-12-05 12:32:54

标签: java android spring spring-boot resttemplate

我试图用长图像数据发送restTemplate。我正在关注this教程代码并获得下一个错误:

W/RestTemplate: POST request for "http://192.168.0.250:8081/server/upload" resulted in 400 (Bad Request); invoking error handler E/ContentValues: 400 Bad Request org.springframework.web.client.HttpClientErrorException: 400 Bad Request

我为Long数据做了简单的restteamplate,但在这里我有一些成功。

以下是我的Android客户端:

protected AnotherPostDTO doInBackground(Void... params) {
Resource resource = new ClassPathResource("res/drawable/bbb.png");
formData = new LinkedMultiValueMap<String, Object>();
formData.add("owners_id", "1");
formData.add("file", resource);

try {
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(formData, requestHeaders);

    ArrayList<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(Arrays.asList(new MappingJackson2HttpMessageConverter(), new FormHttpMessageConverter()));
    RestTemplate restTemplate = new RestTemplate(converters);

    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

    return restTemplate.postForObject(Constants.URLs.UPLOAD_FILE, requestEntity, AnotherPostDTO.class);

} catch (Exception e) {
    Log.e(TAG, e.getMessage(), e);
}
return post;}

我的服务器控制器:

@RequestMapping(value = "postformdata", method = RequestMethod.POST, headers = "Content-Type=multipart/form-data")
public @ResponseBody String handleFormUpload(@RequestParam("description") String description,
                                             @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        byte[] bytes = null;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            System.out.println("taski");
        }
        return "file upload received! Name:[" + description + "] Size:["
                + bytes.length + "]";
    } else {
        return "file upload failed!";
    }
}

和bean:

@Bean
MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    factory.setMaxFileSize("128KB");
    factory.setMaxRequestSize("128KB");
    return factory.createMultipartConfig();
}

有什么想法吗?

0 个答案:

没有答案