在Android上使用Spring上载RoboSpice文件

时间:2013-04-11 09:01:33

标签: android spring rest upload robospice

我一直在努力了解如何使用RoboSpice和Spring将文件上传到我的服务器,但我找不到一个有效的示例。从我找到的一个例子中,我构建了:

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

然而,这给了我错误:

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

好的,所以这似乎表明我需要做一些额外的事情来指示数据应该使用multipart / form-data传输。如果这是正确的,这是怎么做的?如果这不正确,那么规范方法是什么,因为这显然是一种常见需求?

1 个答案:

答案 0 :(得分:4)

就我而言,以下解决了这个问题

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

但是,根据Spring的文档,这不应该是手动设置消息转换器。