您的位置:首页 > 大数据 > 物联网

添加 retrfiot 拦截器Interceptor ,打印服务器返回的json并添加网络请求公共的header

2016-12-03 18:15 786 查看
import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
* 网络切面处理
* Created By: AndroidStudio
* Author :http://write.blog.csdn.net/postedit/53446562
*
*/
public class OkHttpLoggingInterceptor implements Interceptor {

@Override
public Response intercept(Chain chain) throws IOException {

Request.Builder newBuilder = chain
.request()
.newBuilder();

Request request = newBuilder
.addHeader("Content-Type","application/json; charset=utf-8")
.addHeader("Authorization", Bearer )
.build();

String cacheControl=request.cacheControl().toString();
if(TextUtils.isEmpty(cacheControl)){
cacheControl = "public, max-age=60";
}
Response response = chain.proceed(request);

if(BaseApplication.getInstance().isdebug){
Log.e("ssss", "response返回参数" + response.toString());

//添加打印服务器返回的数据
ResponseBody responseBody = response.body();
long contentLength = responseBody.contentLength();
BufferedSource source = responseBody.source();
source.request(Integer.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();

if (contentLength != 0) {
Log.e("服务器返回数据:", ""+buffer.clone().readString(Charset.forName("UTF-8")));
}
}

return response.
newBuilder()
.header("Cache-Control", cacheControl)
.build();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐