public class LoggerInterceptor implements Interceptor {
privateBooleanencrypt=false;//是否加密
publicLoggerInterceptorencrypt(Boolean encrypt) {
this.encrypt= encrypt;
return this;
}
@Override
publicResponseintercept(Chain chain)throwsIOException {
//请求
Request request = chain.request();
RequestBody requestBody = request.body();
Connection connection = chain.connection();
Protocol protocol = connection !=null? connection.protocol() : Protocol.HTTP_1_1;
String requestStartMessage ="--> "+ request.method() +' '+ request.url() +' '+ protocol;
if(requestBody !=null) {
Buffer buffer =newBuffer();
requestBody.writeTo(buffer);
String sBody = buffer.readString(Charset.forName("UTF-8"));
requestStartMessage +=" "+ sBody +" ";
requestStartMessage +=" ("+ requestBody.contentLength() +"-byte body)";
}
LogUtil.net("request: "+ requestStartMessage);
request.header("Content-Type:application/x-www-form-urlencoded; charset=utf-8");
//重新包装
Request newRequest = request;
if(requestBody !=null&& requestBodyinstanceofFormBody) {
newRequest = formatRequest(request);
}
// /*
// *解决okhttp报java.lang.IllegalStateException: closed,java.lang.IllegalStateException: closed,
// *原因为OkHttp请求回调中response.body().string()只能有效调用一次
// * */
//响应
Response response = chain.proceed(newRequest);
//方法一
BufferedSource source = response.body().source();
source.request(Long.MAX_VALUE);// Buffer the entire body.
Buffer buffer = source.buffer();
String responseContent = buffer.clone().readString(Charset.forName("UTF-8"));
LogUtil.net("response-clone: "+ responseContent);
returnresponse;
//方法二
// MediaType mediaType = response.body().contentType();
// responseContent = response.body().string();
// LogUtil.d(TAG, "response-newBuilder: " + responseContent);
// return response.newBuilder()
// .body(ResponseBody.create(mediaType, responseContent))
// .build();
}
/**
*重新包装request
* json &加密
*
*@paramrequest
*@return
*/
privateRequestformatRequest(Request request) {
FormBody formBody = (FormBody) request.body();
//LogUtil.net("formBody-size: " + formBody.size());
//手动格式化字符串
JSONObject json =newJSONObject();
try{
for(inti =0;i < formBody.size();i++) {
json.put(formBody.name(i),formBody.value(i));
}
}catch(JSONException e) {
e.printStackTrace();
}
String jsonValue = json.toString();
//LogUtil.net("new request formBody: " + jsonValue);
if(encrypt) {
try{
jsonValue = EncryptUtil.encrypt(jsonValue.getBytes("utf-8"));
}catch(Exception e) {
e.printStackTrace();
}
}
RequestBody newFormBody =newFormBody.Builder()
.add("json",jsonValue)
.build();
Request newRequest =newRequest.Builder()
.url(request.url())
.headers(request.headers())
.post(newFormBody)
.tag(request.tag())
.build();
returnnewRequest;
}
}