改造 - @Body参数不能与形式或多部分编码中使用能与、或多、形式、参数

2023-09-05 07:54:05 作者:白衣折扇翩翩少年

我米试图让我在其中要包括一个标题,一个表单urlen codeD域和JSON体的请求。 我的改造界面如下

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

当我提出这个要求,我回去异常 @Body 参数不能用于形式或多个部分组成的编码。 我也曾尝试与 @Multipart 注释:

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

和我得到一个抛出:IllegalArgumentException 键,只有一个编码的注释是允许的。

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

推荐答案

这个帖子向我指出了正确的方向的http://计算器.COM / A /一百四十四万六千八百五十六分之二千一百四十二万三千零九十三。 我在身体连接的一切,它作为一个 TypedInput 发送。 所以界面看起来像这样

This post pointed me to the right direction http://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
);

和身体看起来像这样

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