问题描述
我之前已成功使用Square的 Retrofit 进行 @GET
网络API调用,但尝试以<$ c $发送JSON时c> @BODY 在 @POST
调用中,在服务器(Rails)上,JSON显示为参数而不是正文请求。
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.
我的理解是 @BODY
会将该方法参数添加到正文中的请求中。
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
);
提出网络请求:
RestAdapter restAdapter = new RestAdapter.Builder()
.setServer(api_url)
.build();
WebApi webApi = restAdapter.create(AssetsWebApi.class);
Response response = webApi.postScans(auth_token, valid_json);
推荐答案
原来如果你想要 POST 数据作为请求正文的一部分,您需要将API接口方法注释为 @FormUrlEncoded
并将正文内容作为 @Field 如下:
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
);
@Rickster的异步调用:
Async call for @Rickster:
@POST("/api/v1/gear/scans.json")
void postScans(
@Header(HEADER_AUTH) String token,
@Body JsonObject scans,
Callback<PostSuccessResponseWrapper> callback
);
这篇关于改造@Body在HTTP请求中显示为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!