在開(kāi)發(fā)中經(jīng)常會(huì)出現(xiàn),莫名其妙的bug,突然你的app crash了,這時(shí)候我們就需要前后臺(tái)的聯(lián)調(diào),bug也不知道出現(xiàn)在哪里,這是你肯定會(huì)是不是后臺(tái)api的問(wèn)題啊,一個(gè)接著一個(gè)的打印log,如果你使用retrofit的話可能找起來(lái)比較麻煩。不用怕教你兩招,二步搞定。
第一步
1.retrofit大家肯定都有所了解吧,一個(gè)很知名的網(wǎng)絡(luò)請(qǐng)求框架,但是它是以注解方式,來(lái)把url分成兩部分,一個(gè)是BaseUrl和請(qǐng)求的地址拼接在一起的,但是呢,你調(diào)試的時(shí)候不可能每次都去這邊打一下log 那邊斷點(diǎn)調(diào)試。很是麻煩。
2.retrofit嘛他是一個(gè)基于okhttp的網(wǎng)絡(luò)請(qǐng)求框架,那么我們要想拿到這些數(shù)據(jù),肯定通過(guò)okhttp了。從retrofit這里進(jìn)行拿的話可能很費(fèi)勁,但是如果我們從okhttp這里拿這些數(shù)據(jù)的話,那是方便了很多。
3.說(shuō)了也不少了,大家現(xiàn)在知道應(yīng)該從哪里出發(fā)如何獲取這些信息,方便我們調(diào)試,那么我們?cè)谟胦khttp的時(shí)候,知道要配置一些信息吧,構(gòu)建一些東西,這時(shí)候我們只需要配置一下他的攔截器就好。如果你仔細(xì)往里面找的話,可能會(huì)發(fā)現(xiàn)okhttp有這么一個(gè)類HttpLoggingInterceptor,哈哈哈沒(méi)錯(cuò)就是log日志攔截器,他已經(jīng)幫我們寫(xiě)好了。我們只需要吧相應(yīng)的東西打印出來(lái)就好
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
return new OkHttpClient.Builder()
.cache(cache)//添加緩存
.addInterceptor(loggingInterceptor)
.addInterceptor(cacheInterceptor)
.sslSocketFactory(sslContext.getSocketFactory())
.hostnameVerifier(DO_NOT_VERIFY)
// .cookieJar(cookiesManager)
.build();
從上面的代碼可以看到這個(gè)類,只不過(guò)我已經(jīng)吧這個(gè)類提取出來(lái)了,同時(shí)對(duì)立面的log進(jìn)行了一些處理,就變成了我自己的log攔截器了。
第二步
那就是這個(gè)類了,我直接把類扔上來(lái)大家自己看看。立面其實(shí)寫(xiě)的很詳細(xì)
public final class HttpLoggingInterceptor implements Interceptor {
private static final Charset UTF8 = Charset.forName("UTF-8");
public enum Level {
/** No logs. */
NONE,
/**
* Logs request and response lines.
*
* <p>Example:
* <pre>{@code
* --> POST /greeting http/1.1 (3-byte body)
*
* <-- 200 OK (22ms, 6-byte body)
* }</pre>
*/
BASIC,
/**
* Logs request and response lines and their respective headers.
*
* <p>Example:
* <pre>{@code
* --> POST /greeting http/1.1
* Host: example.com
* Content-Type: plain/text
* Content-Length: 3
* --> END POST
*
* <-- 200 OK (22ms)
* Content-Type: plain/text
* Content-Length: 6
* <-- END HTTP
* }</pre>
*/
HEADERS,
/**
* Logs request and response lines and their respective headers and bodies (if present).
*
* <p>Example:
* <pre>{@code
* --> POST /greeting http/1.1
* Host: example.com
* Content-Type: plain/text
* Content-Length: 3
*
* Hi?
* --> END GET
*
* <-- 200 OK (22ms)
* Content-Type: plain/text
* Content-Length: 6
*
* Hello!
* <-- END HTTP
* }</pre>
*/
BODY
}
public interface Logger {
void log(String message);
/** A {@link Logger} defaults output appropriate for the current platform. */
Logger DEFAULT = new Logger() {
@Override public void log(String message) {
Platform.get().log(message);
}
};
}
public HttpLoggingInterceptor() {
this(Logger.DEFAULT);
}
public HttpLoggingInterceptor(Logger logger) {
this.logger = logger;
}
private final Logger logger;
private volatile Level level = Level.NONE;
/** Change the level at which this interceptor logs. */
public HttpLoggingInterceptor setLevel(Level level) {
if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead.");
this.level = level;
return this;
}
public Level getLevel() {
return level;
}
@Override public Response intercept(Chain chain) throws IOException {
Level level = this.level;
Request request = chain.request();
if (level == Level.NONE) {
return chain.proceed(request);
}
boolean logBody = level == Level.BODY;
boolean logHeaders = logBody || level == Level.HEADERS;
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() + ' ' + request.url() + ' ' + protocol;
if (!logHeaders && hasRequestBody) {
requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
}
logger.log(requestStartMessage);
if (logHeaders) {
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) {
logger.log("Content-Type: " + requestBody.contentType());
}
if (requestBody.contentLength() != -1) {
logger.log("Content-Length: " + requestBody.contentLength());
}
}
Headers headers = request.headers();
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)) {
logger.log(name + ": " + headers.value(i));
}
}
if (!logBody || !hasRequestBody) {
logger.log("--> END " + request.method());
} else if (bodyEncoded(request.headers())) {
logger.log("--> 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);
}
logger.log("");
if (isPlaintext(buffer)) {
logger.log(buffer.readString(charset));
logger.log("--> END " + request.method()
+ " (" + requestBody.contentLength() + "-byte body)");
} else {
logger.log("--> END " + request.method() + " (binary "
+ requestBody.contentLength() + "-byte body omitted)");
}
}
}
long startNs = System.nanoTime();
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
logger.log("<-- HTTP FAILED: " + e);
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";
logger.log("<-- " + response.code() + ' ' + response.message() + ' '
+ response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", "
+ bodySize + " body" : "") + ')');
if (logHeaders) {
Headers headers = response.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
logger.log(headers.name(i) + ": " + headers.value(i));
}
if (!logBody || !HttpEngine.hasBody(response)) {
logger.log("<-- END HTTP");
} else if (bodyEncoded(response.headers())) {
logger.log("<-- 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) {
try {
charset = contentType.charset(UTF8);
} catch (UnsupportedCharsetException e) {
logger.log("");
logger.log("Couldn't decode the response body; charset is likely malformed.");
logger.log("<-- END HTTP");
return response;
}
}
if (!isPlaintext(buffer)) {
logger.log("");
logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
return response;
}
if (contentLength != 0) {
logger.log("");
logger.log(buffer.clone().readString(charset));
StringBuilder sb = new StringBuilder();
sb.append("method:")
.append(request.method())
.append(";")
.append("url:")
.append(request.url())
.append(";");
if (!(!logBody || !hasRequestBody||bodyEncoded(request.headers()))){
Buffer buffer1 = new Buffer();
requestBody.writeTo(buffer1);
if (isPlaintext(buffer1)) {
sb.append("body:")
.append(buffer1.readString(charset))
.append(";");
}
}
sb.append("response:")
.append(buffer.clone().readString(charset))
.append(";");
// L.sendLogToServer("httpDetail",sb.toString());
}else{
StringBuilder sb = new StringBuilder();
sb.append("method:")
.append(request.method())
.append(";")
.append("\n")
.append("url:")
.append(request.url())
.append(";")
.append("\n");
if (!(!logBody || !hasRequestBody||bodyEncoded(request.headers()))){
Buffer buffer1 = new Buffer();
requestBody.writeTo(buffer1);
MediaType contentType1 = requestBody.contentType();
if (contentType != null) {
charset = contentType1.charset(UTF8);
}
if (isPlaintext(buffer1)) {
sb.append("body:")
.append(buffer.readString(charset))
.append(";")
.append("\n");
}
}
sb.append("response:")
.append(response.code())
.append(";")
.append("\n");
// L.sendLogToServer("httpDetail",sb.toString());
}
logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
}
}
return response;
}
public void printLogToService(Chain chain, int code) throws IOException {
StringBuilder sb = new StringBuilder();
boolean logBody = level == Level.BODY;
Request request = chain.request();
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
sb.append("method:")
.append(request.method())
.append(";")
.append("url:")
.append(request.url())
.append(";");
if (!logBody || !hasRequestBody) {
android.util.Log.i("djx","--> END " + request.method());
} else if (bodyEncoded(request.headers())) {
android.util.Log.i("djx","--> 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)) {
sb.append("body:")
.append(buffer.readString(charset))
.append(";");
}
}
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
logger.log("<-- HTTP FAILED: " + e);
throw e;
}
ResponseBody responseBody = response.body();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer rspButter = source.buffer();
if (code != 200){
sb.append("response:")
.append(code)
.append(";");
}else{
Charset charset = UTF8;
if (!isPlaintext(rspButter)) {
sb.append("response:")
.append(rspButter.clone().readString(charset))
.append(";");
}
}
// L.sendLogToServer("httpDetail",sb.toString());
android.util.Log.i("djx", "printLogToService: "+sb.toString());
}
/**
* Returns true if the body in question probably contains human readable text. Uses a small sample
* of code points to detect unicode control characters commonly used in binary file signatures.
*/
static boolean isPlaintext(Buffer buffer) throws EOFException {
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; // Truncated UTF-8 sequence.
}
}
private boolean bodyEncoded(Headers headers) {
String contentEncoding = headers.get("Content-Encoding");
return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
}
}
結(jié)束
復(fù)制粘貼即可最后放一下效果圖,從請(qǐng)求開(kāi)始到結(jié)束,完整的url,頭信息,body,response,都很清楚
如果喜歡可以關(guān)注一下。不定期更新技術(shù)文章