Runt
2021-01-18 bf5729bbd51eeb83ebde68c1eaec98a26b9c0ee0
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package com.runt.sharedcode.utils;
 
import android.os.UserManager;
import android.util.Log;
 
 
import java.io.EOFException;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
 
import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okhttp3.internal.platform.Platform;
import okio.Buffer;
import okio.BufferedSource;
 
/**
 * My father is Object, ites purpose of
 *
 * @purpose Created by Runt (qingingrunt2010@qq.com) on 2020-10-21.
 */
 
public class HttpLoggingInterceptor extends PrintLogUtils implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");
 
 
 
    public HttpLoggingInterceptor() {
        TAG = "HttpLogging";
    }
 
 
    @Override
    public Response intercept(Chain chain) throws IOException {
 
        Request request = chain.request()
                .newBuilder()
                //.addHeader("token", UserManager.getInstance().getUserToken())添加了此方法则覆盖了请求头,需要在此再次添加
                .build();
 
        ArrayList<String> logArrays = new ArrayList<>();
        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;
 
        Connection connection = chain.connection();
        Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
        String requestStartMessage = "--> " + request.method() + ' ' + URLDecoder.decode(request.url().toString() ,"UTF-8")+ ' ' + protocol;
        if ( hasRequestBody) {
            requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        logArrays.add(requestStartMessage);
 
        if (hasRequestBody) {
            // Request body headers are only present when installed as a network interceptor. Force
            // them to be included (when available) so there values are known.
            if (requestBody.contentType() != null) {
                logArrays.add("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logArrays.add("Content-Length: " + requestBody.contentLength());
            }
        }
 
        Headers headers = request.headers();
        logArrays.add("---------->REQUEST HEADER<----------");
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logArrays.add(name + ": " + headers.value(i));
            }
        }
 
        if (!hasRequestBody) {
            logArrays.add("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logArrays.add("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
 
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (isPlaintext(buffer)) {
                logArrays.add("---------->REQUEST BODY<----------");
 
                logArrays.add(URLDecoder.decode(buffer.readString(charset), "UTF-8"));
                logArrays.add("--> END " + request.method()
                        + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logArrays.add("--> END " + request.method() + " (binary "
                        + requestBody.contentLength() + "-byte body omitted)");
            }
        }
        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            logArrays.add("<-- HTTP FAILED: " + e);
            new Thread() {
                @Override
                public void run() {
                    printLog(logArrays,false);//线程安全方法,需在新线程执行,避免阻塞当前线程,导致程序无响应
                }
            }.start();
            throw e;//抛出异常,用于请求接收信息
        }
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
 
        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
        logArrays.add("<-- response code:" + response.code() + " message:" + response.message()+" contentlength:"+bodySize  );
        logArrays.add("<-- response url:"+ URLDecoder.decode(response.request().url().toString(),"UTF-8")  );
        logArrays.add("<-- costtimes :  (" + tookMs + "ms"  + ')');
 
 
        if ( !HttpHeaders.hasBody(response)) {
            logArrays.add("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logArrays.add("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
 
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
 
            if (!isPlaintext(buffer)) {
                logArrays.add("");
                logArrays.add("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }
 
            logArrays.add("---------->RESPONSE BODY<----------");
            if (contentLength != 0) {
                logArrays.add(buffer.clone().readString(charset));
            }
 
            logArrays.add("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
        new Thread(() -> {
            printLog(logArrays);//线程安全方法,需在新线程执行,避免阻塞当前线程,导致程序无响应
        }).start();
        return response;
    }
 
 
}