I have been trying to understand how to use RoboSpice with Spring to upload a file to my server, but I cannot find an example that works. From the one example that I did find, I constructed:
class UploadJsonRequest extends SpringAndroidSpiceRequest<APIResponseUpload> {
public UploadJsonRequest() {
super( APIResponseUpload.class );
}
@Override
public APIResponseUpload loadDataFromNetwork() throws Exception {
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
for(org.calflora.observer.model.Attachment a : o.attachments){
parts.add(a.name, new FileSystemResource(a.localPath));
}
//parts.add("record", base);
return getRestTemplate().postForObject(URI, parts, APIResponseUpload.class);
}
}
return new UploadJsonRequest();
However, this gives me the error:
Caused by: org.springframework.web.client.HttpClientErrorException: 404 err: org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/json;charset=UTF-8
OK, so this seems to indicate that I need to do something additional to indicate the data should be transmitted using multipart/form-data. If this is correct, how is this done? If this is not correct, what is the canonical approach, since this is clearly a common need?
In my case, the following solved this problem
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(parts, requestHeaders);
RestTemplate restTemplate = getRestTemplate();
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
return restTemplate.postForObject(URI, requestEntity, APIResponseUpload.class);
However, according to the docs for Spring, this it shouldn't have been necessary to manually set the message converters.