在okhttp3中列印JSON請求體(RequestBody)
阿新 • • 發佈:2019-12-31
在okhttp3中新增攔截器,列印請求的網路資訊是一個通用的需求。下面是列印JSON請求體的方法。
private static String bodyToString(final Request request){
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e) {
return "error";
}
}
複製程式碼
攔截器當中使用
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long startTime = System.currentTimeMillis();
okhttp3.Response response = chain.proceed(chain.request());
long endTime = System.currentTimeMillis();
long duration=endTime-startTime;
okhttp3.MediaType mediaType = response.body().contentType();
String content = response.body().string();
LoggerUtil.info("----------Start----------------");
LoggerUtil.info("| "+request.toString());
String method=request.method();
if ("POST".equals(method)){
LoggerUtil.info("request:\n" + this.bodyToString(request));
}
LoggerUtil.info("| Response:" + content);
LoggerUtil.info("----------End:"+duration+"毫秒----------");
return response.newBuilder()
.body(okhttp3.ResponseBody.create(mediaType,content))
.build();
}
複製程式碼