Search code examples
androidjsonjacksonandroid-annotations

Why does my multipart form-data get converted to JSON?


I need to do a POST towards an API where multipart form-data is required with one record where the key 'json' and the value is a string containing a json object.

I'm trying to do it using AndroidAnnotations like this:

@Post(API_CREATE_PATH + API_KEY)
CreateResponse create(Map<String,String> map);

A valid request looks like the following, done with Postman:

Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="json"

{"test":"data"}
----WebKitFormBoundary7MA4YWxkTrZu0gW

Instead of that, the actual request body contains "json":"{"test":"data"}", and I can't understand why.


Solution

  • You can send a multi-part POST in this way, as explained in the wiki.

    @Rest(rootUrl = "http://company.com/ajax/services", converters = FormHttpMessageConverter.class)
    public interface MyRestClient extends RestClientHeaders {
    
      @Post(API_CREATE_PATH + API_KEY)
      @RequiresHeader(HttpHeaders.CONTENT_TYPE)
      CreateResponse create(MultiValueMap<String,Object> map);
    }
    
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.set("test","data");
    
    client.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE);
    
    client.create(map);