doum
6 天以前 2b287056e2f59518888d05a1bbc7e5a55fbd84d5
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
package com.doumee.lib_coremodel.http.interceptor;
 
import java.io.IOException;
 
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import timber.log.Timber;
 
/**
 * @author <a href="mailto:jenly1314@gmail.com">Jenly</a>
 */
public class LogInterceptor implements Interceptor {
 
    private static String multipartType = "multipart";
 
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Timber.i(String.format("%1$s -> %2$s",request.method(),request.url()));
 
        if(request.headers() != null){
            Timber.i("Headers:" + request.headers());
        }
 
        if(request.body() != null){
            MediaType mediaType = request.body().contentType();
            if(mediaType != null){
                Timber.i("RequestContentType:" + mediaType);
            }
            if(mediaType == null || !multipartType.equalsIgnoreCase(mediaType.type())){
                Timber.i("RequestBody:" + bodyToString(request.body()));
            }
        }
 
        Response response = chain.proceed(chain.request());
        MediaType mediaType = response.body().contentType();
        String responseBody = response.body().string();
        //todo 隐藏返回数据
        //Timber.d("ResponseBody:" + responseBody);
 
        return response.newBuilder()
                .body(ResponseBody.create(mediaType, responseBody))
                .build();
    }
 
    private String bodyToString(final RequestBody request) {
        if(request != null){
            try {
                final RequestBody copy = request;
                final Buffer buffer = new Buffer();
                copy.writeTo(buffer);
                return buffer.readUtf8();
            } catch (final Exception e) {
                Timber.e(e,"Did not work.");
            }
        }
        return null;
    }
}