OKHttp简单的日志拦截器

````java

public class MainActivityextends AppCompatActivity {

        private static final StringTAG =".MainActivity";

        private ButtonbtnSet;

        @Override

        protected void onCreate(Bundle savedInstanceState) {

                super.onCreate(savedInstanceState);

                setContentView(R.layout.activity_main);

                initView();

        }

        private void initView() {

                //创建一个按钮

                btnSet = (Button) findViewById(R.id.btn_set);

                btnSet.setOnClickListener(new View.OnClickListener() {

                @Override

                    public void onClick(View v) {

                            //运行okhttp网络请求

                            initData();

                    }

                });

        }

        private void initData() {

                //添加网址,请求头等等。(我这边没有设置请求头。)

                Request build =new Request.Builder()

                .url("https://www.bilibili.com/index/ding.json")

                .build();

                //OkHttp网络请求主体

                new OkHttpClient.Builder()

                //添加程序拦截器

                .addNetworkInterceptor(new Lnterceptor())

                .build()

                .newCall(build)

                .enqueue(new Callback() {

                @Override

                public void onFailure(Call call, IOException e) {

                }

                @Override

                public void onResponse(Call call, Response response)throws IOException {

                            //成功之后解析数据

                             //response.body().string(),只能使用1次

                            Log.d(TAG,"成功回调日志:"+response.body().string());

                }

        });

    }

    //日志拦截器,需要打印返回的数据

    private class Lnterceptorimplements Interceptor {

        @Override

            public Response intercept(Chain chain)throws IOException {

                //Chain : 链条的意思,通过它可以拿到request对象,还可以发起网络请求拿到response

                //拿到请求对象

                Request request = chain.request();

                //发起网络请求

                Response proceed = chain.proceed(request);

                //response.body().string(),只能使用1次

                //如果这里使用了onResponse成功回调就不能拿使用了

                //Log.d(TAG, "intercept: "+response.body().string());

                //=====================================

                 //相当于是将body拷贝一份

                String string = proceed.peekBody(1024).string();

                Log.d("TAG","拦截器:"+string);

                return proceed;

            }

    }

}


````

你可能感兴趣的:(OKHttp简单的日志拦截器)