Ok网络工具类,日志拦截器,应用拦截器

public class OkHttpUtls {

    private static OkHttpUtls okHttpUtls=null;

    public OkHttpUtls() {
    }

    public static OkHttpUtls getInStence(){
        if(okHttpUtls==null){
            synchronized (OkHttpUtls.class){
                okHttpUtls=new OkHttpUtls();
            }
        }

        return okHttpUtls;
    }


    //ok
    private static OkHttpClient okHttpClient=null;

    public static synchronized  OkHttpClient getOkHttp(){
        HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                 Log.d("aa",message);
            }
        });

        if(okHttpClient==null){
            okHttpClient=new OkHttpClient.Builder()
                    .addInterceptor(httpLoggingInterceptor)
                    //应用拦截器
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request request=chain.request().newBuilder()
                                    .addHeader("source","android")
                                    .build();
                            return chain.proceed(request);
                        }
                    })
                    .build();
        }
        return okHttpClient;
    }



    //get
    public static void getData(String url, Callback callback){
        OkHttpClient okHttp = getOkHttp();
        Request request=new Request.Builder().url(url).build();
        Call call = okHttp.newCall(request);
        call.enqueue(callback);

    }


    //post
    public static void postData(String url, Map<String,String> map,Callback callback){
        //ok对象
        OkHttpClient okHttp = getOkHttp();
        //请求体
        FormBody.Builder builder = new FormBody.Builder();
        for (String key:map.keySet()){
            builder.add(key,map.get(key));
        }
        FormBody build = builder.build();
        //请求
        Request request=new Request.Builder().post(build).url(url).build();
        Call call = okHttp.newCall(request);
        call.enqueue(callback);


    }






}

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值