单例 拦截器 封装ok请求

   //设置单例模式  拦截器   封装网络请求
public class ShowUtils {
        //设置单例

        //私有的静态的成员变量  只声明不创建
       private static ShowUtils showUtils=null;
       private static ShowUtils showUtils1;

          //私有的构造方法
    public ShowUtils() {
    }
          //返回公共静态的实例方法
     public  static  ShowUtils showUtils(){
             if (showUtils==null){
                 synchronized (ShowUtils.class){
                      if (showUtils==null){
                 showUtils1 = new ShowUtils();
                      }
                 }
             }
            return showUtils;
     }

           private static OkHttpClient okHttpClient=null;
         //返回ok
          public synchronized  static  OkHttpClient getokHttpClient(){
                  if (okHttpClient==null){
   HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                          @Override
                          public void log(String message) {
                          //*  Log.i("xxx",message);*//*
                          }
                      });
                       //创建日志拦截器模式
     httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
     
       okHttpClient =new OkHttpClient.Builder().
       //应运拦截器
       .addInterceptor(new Interceptor() {
       @Override
      public Response intercept(Chain chain) throws IOException {
        Request build = chain.request().newBuilder()
                .addHeader("source", "android")
                .build();
        return chain.proceed(build);
     }
  })
       addInterceptor(httpLoggingInterceptor)
       .build();
                  }
                  return okHttpClient;
          }

          //网络请求get方法
       public static void  doget(String url, Callback callback){
               OkHttpClient  okHttpClient = getokHttpClient();
           Request build1 = new Request.Builder().url(url).build();
           Call call = okHttpClient.newCall(build1);
                 call.enqueue(callback);
       }

     //网络请求post请求
     public void  dopost(String url, Map<String,String>mapdate, Callback callback){
         OkHttpClient  okHttpClient = getokHttpClient();
            FormBody.Builder builder = new FormBody.Builder();
                   //遍历集合
           for(String key : mapdate.keySet()){
               builder.add(key,mapdate.get(key));
           }
                 //构建
                 FormBody build1 = builder.build();

         Request build = new Request.Builder().url(url).post(build1).build();
         Call call = okHttpClient.newCall(build);
                   call.enqueue(callback);
     }

}
 //接口回调
 public interface  Show{
          //抽象方法
       void  getdate(String date);
 }
 //声明
 private Show show;
 
public void setShow(Show show) {
    this.show = show;
}

private Map<String,String> map=new HashMap<>();
map.put(“phone”, name);
map.put(“pwd”, pwd);

猜你喜欢

转载自blog.csdn.net/weixin_43882910/article/details/87540779