5

I've previously used Square's Retrofit successfully for a @GET web API call but when trying to send JSON as the @BODY in a @POST call, on the server (Rails) the JSON is showing up as Parameters rather than the body request.

My understanding is that @BODY will add that method parameter to the request in the body.

Any idea what I'm doing wrong?

WebApi:

@POST("/api/v1/gear/scans.json")
Response postScans(
    @Header(HEADER_AUTH) String token,
    @Body JsonObject scans
);

Make web request:

RestAdapter restAdapter = new RestAdapter.Builder()
    .setServer(api_url)
    .build();
WebApi webApi = restAdapter.create(AssetsWebApi.class);     
Response response = webApi.postScans(auth_token, valid_json);
JJD
  • 50,076
  • 60
  • 203
  • 339
saywhatnow
  • 1,026
  • 2
  • 15
  • 26

1 Answers1

12

Turns out that if you want to POST data as part of the request body, you need to annotate the API interface method as @FormUrlEncoded and pass the content of the body as a @Field as below:

@FormUrlEncoded
@POST("/api/v1/gear/scans.json")
Response postScans(
    @Header(HEADER_AUTH) String token,
    @Field("scans") JsonArray scans
);

Async call for @Rickster:

@POST("/api/v1/gear/scans.json") 
void postScans(
    @Header(HEADER_AUTH) String token,
    @Body JsonObject scans,
    Callback<PostSuccessResponseWrapper> callback
);
JJD
  • 50,076
  • 60
  • 203
  • 339
saywhatnow
  • 1,026
  • 2
  • 15
  • 26
  • How do you do an asynchronous version of this? When I add a callback, I get an exception - http://stackoverflow.com/questions/22572301/retrofit-throwing-illegalargumentexception-exception-for-asynchronous-formurlenc – Rickster Mar 22 '14 at 02:17
  • @Rickster I suspect your issue is to do with your `@DELETE` annotation but I'm not familiar with that - I've only ever done `@GET` & `@POST` calls. My async call is edited above. – saywhatnow Mar 23 '14 at 21:35
  • Great answer. It is strange though that you can not do `@Body String param_name`, but insted you have to do `@Field("param") String param_name` and before `@POST` you need to annotate `@FormUrlEncoded` ;) but because this is the perfect solution, i am ok with that. Thank You! – virusss8 Mar 25 '15 at 12:16