一.依赖拦截日志地址
compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'
二.定义拦截器中的网络日志工具
依赖拦截日志地址,后就能识别HttpLoggingInterceptor。
之后定义一个要打印日志的类。
public class HttpLogger implements HttpLoggingInterceptor.Logger {
@Override
public void log(String message) {
Log.d("HttpLogInfo", message);//okHttp的详细日志会打印出来
}
}
三.创建日志对象,并且放到okHttp请求对象中
Request request = new Request.Builder().url(urlString).build();
//设置拦截器
new OkHttpClient.Builder().addNetworkInterceptor(new HttpLoggingInterceptor(new HttpLogger()).setLevel(HttpLoggingInterceptor.Level.BODY))
.writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(10,TimeUnit.SECONDS)
.connectTimeout(10,TimeUnit.SECONDS)
.build().newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String string = response.body().string();
Object gson = OKHttpUtil.getGson(string, cl);
handler.sendMessage(handler.obtainMessage(0,gson));
}
});
四.结果