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;
|
}
|
|
|
}
|