etrofit做网络请求特别爽,然而当我们用retrofit的时候发现不能直接log打印出网络请求返回的数据内容。比如说返回的是json数据,然而retrofit的Gson工厂早就自动把这些数据给解析掉了,无从获得这个原始数据(有时候用接口测试工具GetMan或者PostMan也不能获得完全准确的数据,笔者亲试过)
咋办?
借助HttpLoggingInterceptor类!
步骤
1.首先导入库
implementation'com.squareup.okhttp3:okhttp:3.7.0'
implementation 'com.squareup.retrofit2:retrofit:2.0.1'
implementation 'com.squareup.retrofit2:converter-gson:2.0.1'
implementation'com.squareup.okhttp3:logging-interceptor:3.4.1'
2.初始化HttpLoggingInterceptor
/*
**打印retrofit信息部分
*/
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new
HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
//打印retrofit日志
Log.e("RetrofitLog","retrofitBack = "+message);
}
});
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
//okhttp设置部分,此处还可再设置网络参数
.addInterceptor(loggingInterceptor)
.build();
3.retrofit请求部分(此部分只有一句.client(client)起了打印作用)
/*
**retrofit请求部分
*/
MyRequest.UserConfigPrimarykeyBean userConfigPrimarykeyBean=new MyRequest.UserConfigPrimarykeyBean();
userConfigPrimarykeyBean.setPhone("13411982971");
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("http://www.xinius.cn:8084/appdemo/")
.client(client)//此client是为了打印信息
.addConverterFactory(GsonConverterFactory.create())
.build();
NetApi netApi=retrofit.create(NetApi.class);
Call<HttpBack> call=netApi.request(userConfigPrimarykeyBean);
Log.e(TAG, "发送请求 ");
call.enqueue(new Callback<HttpBack>() {
@Override
public void onResponse(Call<HttpBack> call, retrofit2.Response<HttpBack> response) {
showResponse("请求发送成功,返回信息为: "+response.body().getData().getList().get(0).getConfigValue());
}
@Override
public void onFailure(Call<HttpBack> call, Throwable t) {
showResponse("请求失败");
Log.e(TAG, "请求失败 " );
}
});