- 需求:
開發(fā)新項目時当宴,拿到接口文檔裁厅,需要請求消息體是json類型的
可能你這么寫過post:
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) {
}
});
這是表單提交搪搏,你提交上去的其實是id=123&name=ksi
這么個東西。
如果要提交的是json那么自然要改變請求體了
好堵幽,有的同學(xué)可能會搜索以下問題:怎么查看/更改/添加請求頭、請求體弹澎、響應(yīng)體朴下?
我的版本是:retrofit2.1.0,2.0以前的做法可能不一樣苦蒿。
首先殴胧,在你的build.gradle下面依賴這玩意
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
然后配置client,添加攔截器佩迟,第一個攔截器是用于添加請求頭的团滥,第二個就是打印日志了
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);
} //下面是關(guān)鍵代碼
}).addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
好报强,我們來干正經(jīng)事了灸姊,json格式的請求,參數(shù)注解用@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秉溉,里面包含了你要傳給服務(wù)器的各個鍵值對力惯,然后根據(jù)接口文檔的請求格式,直接拼接上相應(yīng)的東西就行了
//比如{"data":{這里面是參數(shù)}}召嘶,那就在外面拼上大括號和"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父晶,大功告成,來看看打印結(jié)果吧
看到第三行了么弄跌,那就是自定義添加的請求頭甲喝,第四行就是json格式的請求體了
<---200 OK下面是響應(yīng)體。