改造 - @Body 参数不能与表单或多部分编码一起使用 [英] Retrofit - @Body parameters cannot be used with form or multi-part encoding
问题描述
我正在尝试发出一个请求,其中我想包含一个 Header 、一个 form-urlencoded 字段和一个 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.
推荐答案
这篇文章为我指明了正确的方向 https://stackoverflow.com/a/21423093/1446856.我附加了正文中的所有内容并将其作为 TypedInput
发送.
所以界面看起来像这样
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
);
身体看起来像这样
String bodyString = jsonBody + "?grant_type=" +
grantType + "&scope=" + scope;
TypedInput requestBody = new TypedByteArray(
"application/json", bodyString.getBytes(Charset.forName("UTF-8")));
这篇关于改造 - @Body 参数不能与表单或多部分编码一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!