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

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();

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值