67

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.

4

5 に答える 5

103

この問題が発生した場合は、インターフェイスの@FormUrlEncodedを削除する必要があります。お役に立てれば。

于 2016-04-19T08:26:56.710 に答える
23

この投稿は、私を正しい方向に向けましたhttps://stackoverflow.com/a/21423093/1446856。本体に全て付けて発送致しますTypedInput
したがって、インターフェースは次のようになります

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

そして体はこんな感じ

String bodyString = jsonBody + "?grant_type=" + 
    grantType + "&scope=" + scope;
TypedInput requestBody = new TypedByteArray(
    "application/json", bodyString.getBytes(Charset.forName("UTF-8")));
于 2014-12-08T09:47:31.627 に答える