- Requirement: When developing a new project, to get the interface document, the request message body needs to be json type
Maybe you wrote a post like this:
interface NService {
@FormUrlEncoded
@POST("alarmclock/add.json")
Call<ResponseBody> getResult(@FieldMap Map<String, Object> params);
}
Retrofit retrofit = new Retrofit.Builder().baseUrl(URL).client(client).build();
NService nService = retrofit.create(NService.class);
Map<String, Object> params = new HashMap<>();///
params.put("id", "123");
params.put("name", "ksi");//
Call<ResponseBody> call = nService.getResult(params); //
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
This is a form submission, and what you submit is actually id=123&name=ksi
such a thing.
If you want to submit json, then it is natural to change the request body
Well, some students may search for the following questions: How to view/change/add request headers, request bodies, and response bodies ?
My version is: retrofit2.1.0, the practice before 2.0 may be different.
First, rely on this thing under your build.gradle compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
and then configure the client, add interceptors, the first interceptor is used to add request headers, and the second is to print logs
OkHttpClient client = new OkHttpClient().newBuilder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("creater_oid", "123411") //这里就是添加一个请求头
.build();
// Buffer buffer = new Buffer(); 不依赖logging,用这三行也能打印出请求体
// request.body().writeTo(buffer);
// Log.d(getClass().getSimpleName(), "intercept: " + buffer.readUtf8());
return chain.proceed(request);
} //下面是关键代码
}).addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
Okay, let's get down to business, the request in json format, the parameter annotation is @Body
interface ApiService {
@POST("add.json")
Call<ResponseBody> add(@Body RequestBody body);
}
Retrofit retrofit = new Retrofit.Builder().baseUrl(URL).client(client).build();
ApiService apiService = retrofit.create(ApiService.class);
//new JSONObject里的getMap()方法就是返回一个map,里面包含了你要传给服务器的各个键值对,然后根据接口文档的请求格式,直接拼接上相应的东西就行了
//比如{"data":{这里面是参数}},那就在外面拼上大括号和"data"好了
RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"),
"{\"data\":"+new JSONObject(getMap()).toString()+"}");
Call<ResponseBody> call = apiService.add(requestBody);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
Log.d(getClass().getSimpleName(), "onResponse: ----" + response.body().string());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d(getClass().getSimpleName(), "onFailure: ------" + t.toString());
}
});
OK, you're done, let's take a look at the print result
See the third line, that is the custom added request header, and the fourth line is the request body in json format
<---200 OK The following is the response body.
Author: futaba_anzu
Link: http://www.jianshu.com/p/95a7361016ff
Source: Jianshu The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.