OkHttp-拦截器

下面是关于OkHttp-拦截器的介绍和代码,就只用一个类就可以实现OkHttp-拦截器的效果

1.创建一个HttpUtils 的类,在HttpUtils 中实现OkHttp-拦截器的具体方法

public class HttpUtils {
    //提供一个本地Http工具类
    public static HttpUtils httpUtils;
    private final OkHttpClient httpClient;
    private final Handler handler;

    //私有化构造函数
    private HttpUtils() {
        //主线程handler
        handler = new Handler(Looper.getMainLooper());
        httpClient = new OkHttpClient.Builder()
                .readTimeout(5000, TimeUnit.MILLISECONDS)
                .writeTimeout(5000, TimeUnit.MILLISECONDS)
                .connectTimeout(5000, TimeUnit.MILLISECONDS)
                .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
                //Application拦截器
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        HttpUrl url = request.url();
                        String s = url.url().toString();
                        //---------请求之前-----
                        Log.d("Interceptor", "app interceptor:begin");
                        Response response = chain.proceed(request);
                        //---------请求之后-----
                        Log.d("Interceptor", "app interceptor:end");
                        return response;
                    }
                })
                //Network拦截器
                .addNetworkInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        //---------请求之前-----
                        Log.d("Interceptor", "network interceptor:begin");
                        Response response = chain.proceed(request);
                        //---------请求之后-----
                        Log.d("Interceptor", "network interceptor:end");
                        return response;
                    }
                })
                .build();
    }
        //提供公有方法供外部类访问
    public static HttpUtils getHttpUtils() {
        //Dcl模式 懒汉式
        if (httpUtils == null) {
            synchronized (HttpUtils.class) {//线程锁
                if (httpUtils == null) {
                    return httpUtils = new HttpUtils();
                }
            }
        }
        return httpUtils;
    }

    //异步get请求--doGet
    public void doGet(String url, final IOKHttpUtilsCallBack iokHttpUtilsCallBack) {
        Request request = new Request.Builder().url(url).get().build();
        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (iokHttpUtilsCallBack != null) {
                    iokHttpUtilsCallBack.onFailure(e.getMessage());
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()) {
                    final String json = response.body().string();
                    if (iokHttpUtilsCallBack != null) {
                        //切换到主线程
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                iokHttpUtilsCallBack.onResponse(json);
                            }
                        });
                    }
                } else {
                    if (iokHttpUtilsCallBack != null) {
                        //切换到主线程
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                iokHttpUtilsCallBack.onFailure("网络异常");
                            }
                        });
                    }
                }
            }
        });
    }
    //异步post
    public void doPost(String url, Map<String, String> map, final IOKHttpUtilsCallBack ioKhttpUtilsCallback) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder()
                .post(formBody)
                .url(url)
                .build();
        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (ioKhttpUtilsCallback != null) {
                    //切换到主线程
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            ioKhttpUtilsCallback.onFailure(e.getMessage());
                        }
                    });
                }
            }


            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response != null && response.isSuccessful()) {
                    final String json = response.body().string();
                    if (ioKhttpUtilsCallback != null) {
                        //切换到主线程
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ioKhttpUtilsCallback.onResponse(json);
                            }
                        });
                    }


                } else {
                    if (ioKhttpUtilsCallback != null) {
                        //切换到主线程
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                ioKhttpUtilsCallback.onFailure("网络异常");
                            }
                        });
                    }
                }
            }
        });
    }

    //接口回调
    public interface IOKHttpUtilsCallBack {
        void onFailure(String error);

        void onResponse(String json);
    }
}

在一个类中就能实现这些效果非常简单,希望我的这篇博客能到帮你们,其实我感觉我这篇博客写的不太好还望大神多多见谅,最好能指点一下,广府城先在这谢谢你们了
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43053718/article/details/85947670