Retrofit @Body showing up as parameter in HTTP request

有些话、适合烂在心里 提交于 2019-12-23 11:00:50

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/18908175/retrofit-body-showing-up-as-parameter-in-http-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!