个人觉得这个例子是拦截器很好的入门,虽然直接使用下面三行代码就可以获得想要的Log信息
if(BuildConfig.DEBUG){
//log拦截器
HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(loggingInterceptor);
}
下面转载自:
http://blog.csdn.net/it_talk/article/details/51734507
日志拦截器
retrofit是使用okhttp3,做为网络请求,okhttp3有个Interceptor接口,可以对请求和响应进行拦截。通过这个机制,我们可以设计自己的一套日志拦截器,打印一些必要的信息。
public class LogInterceptor implements Interceptor{
public static final String TAG = "LogInterceptor.java";
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String url = request.url().toString();
String method = request.method();
long t1 = System.nanoTime();
HLog.d(TAG,String.format(Locale.getDefault(),"Sending %s request [url = %s]",method,url));
RequestBody requestBody = request.body();
if(requestBody!= null) {
StringBuilder sb = new StringBuilder("Request Body [");
okio.Buffer buffer = new okio.Buffer();
requestBody.writeTo(buffer);
Charset charset = Charset.forName("UTF-8");
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(charset);
}
if(isPlaintext(buffer)){
sb.append(buffer.readString(charset));
sb.append(" (Content-Type = ").append(contentType.toString()).append(",")
.append(requestBody.contentLength()).append("-byte body)");
}else {
sb.append(" (Content-Type = ").append(contentType.toString())
.append(",binary ").append(requestBody.contentLength()).append("-byte body omitted)");
}
sb.append("]");
HLog.d(TAG, String.format(Locale.getDefault(), "%s %s", method, sb.toString()));
}
Response response = chain.proceed(request);
long t2 = System.nanoTime();
HLog.d(TAG,String.format(Locale.getDefault(),"Received response for [url = %s] in %.1fms",url, (t2-t1)/1e6d));
HLog.d(TAG,String.format(Locale.CHINA,"Received response is %s ,message[%s],code[%d]",response.isSuccessful()?"success":"fail",response.message(),response.code()));
ResponseBody body = response.body();
BufferedSource source = body.source();
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();
Charset charset = Charset.defaultCharset();
MediaType contentType = body.contentType();
if (contentType != null) {
charset = contentType.charset(charset);
}
String bodyString = buffer.clone().readString(charset);
HLog.d(TAG,String.format("Received response json string [%s]",bodyString));
return response;
}
static boolean isPlaintext(Buffer buffer){
try {
Buffer prefix = new Buffer();
long byteCount = buffer.size() < 64 ? buffer.size() : 64;
buffer.copyTo(prefix, 0, byteCount);
for (int i = 0; i < 16; i++) {
if (prefix.exhausted()) {
break;
}
int codePoint = prefix.readUtf8CodePoint();
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false;
}
}
return true;
} catch (EOFException e) {
return false;
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
在上面的实现中,打印了请求的url、请求方法(get\post\put\delete…)、响应时间、响应状态、响应内容等。这里需要主要的是,在打印响应内容体的时候,或许你会遇到下面这个异常:
java.lang.IllegalStateException: closed
这是因为你打印的时候直接调用了ResponseBody.string(),我们看下源码的实现
public final String string() throws IOException {
return new String(bytes(), charset().name());
}
它调用了bytes(),我在接着看下
public final byte[] bytes() throws IOException {
long contentLength = contentLength();
if (contentLength > Integer.MAX_VALUE) {
throw new IOException("Cannot buffer entire body for content length: " + contentLength);
}
BufferedSource source = source();
byte[] bytes;
try {
bytes = source.readByteArray();
} finally {
Util.closeQuietly(source);
}
if (contentLength != -1 && contentLength != bytes.length) {
throw new IOException("Content-Length and stream length disagree");
}
return bytes;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
看到finally部分,它已经将 BufferedSource 关闭掉了,这样到我们自己接口真正要处理的时候,它就会报错了,已经关闭的缓冲区就不能操作了。
那么上面LogInterceptor实际上是clone了一份BufferedSource 进行操作,这样不影响原来的BufferedSource。
也可以使用下面第二种方法,原理相同:
ResponseBody originalBody = response.body();
ResponseBody body = response.peekBody(originalBody.contentLength());
bodyString = body.string();
OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
builder.addNetworkInterceptor(new NetworkInterceptor())
if(BuildConfig.DEBUG){
//日志拦截器
builder.addNetworkInterceptor(new LogInterceptor())
}
OkHttpClient client = builder.build()
retrofit = new Retrofit.Builder()
.baseUrl(APIService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(client)
.build()