OkHttp二次封装+拦截器

OkHttpUtils


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值