当前位置 : 主页 > 编程语言 > java >

okhttp拦截post日志

来源:互联网 收集:自由互联 发布时间:2022-06-23
import java.io.IOException; import java.net.URLDecoder; import cn.mvp.mlibs.log.Log; import okhttp3.FormBody; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody
import java.io.IOException;
import java.net.URLDecoder;

import cn.mvp.mlibs.log.Log;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

public class LogInterceptor implements Interceptor {

public static String TAG = "调用信息";

@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long startTime = System.currentTimeMillis();
Response response = chain.proceed(chain.request());
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
MediaType mediaType = response.body().contentType();
String content = response.body().string();
Log.d(TAG, "\n");
Log.d(TAG, "----------Start----------------");
Log.d(TAG, "| " + request.toString());
String method = request.method();
if ("POST".equals(method)) {
if (request.body() instanceof FormBody) {
StringBuilder sb = new StringBuilder();
FormBody body = (FormBody) request.body();
for (int i = 0; i < body.size(); i++) {
sb.append(body.encodedName(i)).append("=").append(body.encodedValue(i)).append(",");
}
sb.delete(sb.length() - 1, sb.length());
Log.d(TAG, "| RequestParams:{" + sb.toString() + "}");
} else {
Buffer buffer = new Buffer();
request.body().writeTo(buffer);
buffer.flush();
Log.d(TAG, "| RequestParams:{" + URLDecoder.decode(buffer.readUtf8(), "utf-8") + "}");
}
}
Log.d(TAG, "| Response:" + content);
Log.d(TAG, "----------End:" + duration + "毫秒----------");
return response.newBuilder().body(ResponseBody.create(mediaType, content)).build();
}

private int last;

private String randomKey() {
int random = (int) (10 * Math.random());
if (random == last) {
random = (random + 1) % 10;
}
last = random;
return String.valueOf(random);
}
}

 


上一篇:你会跟同事/朋友吃饭去吗
下一篇:没有了
网友评论