OkHttpUtil工具类封装get/post请求 单例模式 以及 请求拦截

   

//方法私有化

private OkhttpUtile(){
        okHttpClient = new OkHttpClient.Builder().addInterceptor(new MyInterceptor()).build();
    }

 

//单例模式

  public static synchronized OkhttpUtile getInstace(){
        if(utile == null){
            utile = new OkhttpUtile();
        }
        return utile;
    }

 

//封装请求数据方法
public static void doGet(String path, Callback callback){

    OkHttpClient okHttpClient = new OkHttpClient();
    Request builder = new Request.Builder()
            .url(path)
            .get()
            .build();

    okhttp3.Call call = okHttpClient.newCall(builder);
    call.enqueue(callback);


}

 

//注册 登录工具类
public static void doPost(String 参数, String 参数, String 参数, Callback callback){

    Log.e("tag",path);
    OkHttpClient okHttpClient = new OkHttpClient();
    //创建FormBoday对象
    FormBody.Builder formbody = new FormBody.Builder();
    //添加参数
    formbody.add("参数",参数);
    formbody.add("参数",参数);
    //用FormBody创建构建模式
    RequestBody body = formbody.build();
    Request request = new Request.Builder()
            .post(body)
            .url(path)
            .build();
    //创建Call对象
    Call call = okHttpClient.newCall(request);
    call.enqueue(callback);
}

//拦截器拦截请求

    public class MyInterceptor implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Log.e("tag" ,"request url = " + request.url());
            Response response = chain.proceed(request);
            return response;
        }
    }

你可能感兴趣的:(安卓)