Retrofit - @Body parameters cannot be used with form or multi-part encoding

余生颓废 提交于 2019-12-29 18:17:21

问题


I m trying to make a request in which I want to include a Header , a form-urlencoded field and a json body. My Retrofit interface is as follows

@FormUrlEncoded
@POST("/api/register")
Observable<RegisterResponse> register(
    @Header("Authorization") String authorization, 
    @Field("grant_type") String grantType, 
    @Body RegisterBody body
);

When I make this request I get back exception @Body parameters cannot be used with form or multi-part encoding.
I have also tried with the @Multipart annotation:

@Multipart
@FormUrlEncoded
@POST("/api/register")
Observable<RegisterResponse> register(
    @Header("Authorization") String authorization, 
    @Part("grant_type") TypedString grantType, 
    @Body RegisterBody body
);

and I get an IllegalArgumentException and only one encoding annotation is allowed.


回答1:


maybe this could help some people, if you have this trouble, you should remove @FormUrlEncoded of your interface. Hope this helps.




回答2:


This post pointed me to the right direction https://stackoverflow.com/a/21423093/1446856. I attached everything in the body and send it as a TypedInput.
So the interface looks something like this

@POST("/api/register")
@Headers({ "Content-Type: application/json;charset=UTF-8"})
Observable<RegisterResponse> register(
    @Header("Authorization") String authorization,
    @Body TypedInput body
);

and the body looks something like this

String bodyString = jsonBody + "?grant_type=" + 
    grantType + "&scope=" + scope;
TypedInput requestBody = new TypedByteArray(
    "application/json", bodyString.getBytes(Charset.forName("UTF-8")));



回答3:


I solved this problem by adding the field into

@POST("/api/register") 

like this:

@POST("/api/register?grantType=value")

it's not a good solution, but may be useful.




回答4:


Send Authentication header with json Body to API sample code in Kotlin :

 @POST("/api/user/sendlist/")
    fun callSendJsonListPost(
                      @Header("Authheader") header: String,
                      @Body list: StringBuilder
                      )
        : Observable<EntityModelUserslist>


来源:https://stackoverflow.com/questions/27317096/retrofit-body-parameters-cannot-be-used-with-form-or-multi-part-encoding

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