美文网首页
Retrofit的简单封装

Retrofit的简单封装

作者: 冬絮 | 来源:发表于2019-02-21 13:35 被阅读7次

    OKhttp拦截器

    1. 导入依赖

       //OKHttp拦截器
       implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
      
    2. 创建HttpLoggingInterceptor实例

       val interceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
           try {
               val text = URLDecoder.decode(message, "utf-8")
               Log.e("HttpLoggingInterceptor", text)
           } catch (e: UnsupportedEncodingException) {
               e.printStackTrace()
               Log.e("HttpLoggingInterceptor", message)
           }
       })
       //这行必须加 不然默认不打印
       interceptor.level = HttpLoggingInterceptor.Level.BODY
      
    3. 创建OkHttpClient,并添加拦截器

       val okHttpClient= OkHttpClient.Builder()
           .connectTimeout(20, TimeUnit.SECONDS)
           .writeTimeout(20, TimeUnit.SECONDS)
           .readTimeout(20, TimeUnit.SECONDS)
           .retryOnConnectionFailure(true)
           .addInterceptor(interceptor)
           .build()
      
    4. 创建retrofit实例,并设置OkHttpClient

       var retrofit = Retrofit.Builder()
           .baseUrl(BASE_URL)
           .addConverterFactory(GsonConverterFactory.create())
           .client(okHttpClient)
           .build()
      

    ApiServece封装

        public interface ApiService {
            @GET("category-list")
            Call<AppCategoryBean> getCategory();
        
            @GET("category")
            Call<AppCategoryDetailBean> getCategoryDetail(@Query("id") int id);
            
            @GET("info")
            Call<AppDetailBean> getAppdetail(@Query("appid") int appid);
        }
    

    Retrofit简单封装

     public class RetrofitHelper {
        
            private static final String BASE_URL = "http://api.mvlink.vip:8083/appstore/";
            private static RetrofitHelper retrofitHelper;
            public Retrofit retrofit;
            private RetrofitHelper() {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(getOkHttpClient())
                        .build();
            }
        
            public static RetrofitHelper getInstance() {
                if (retrofitHelper == null) {
                    synchronized (RetrofitHelper.class) {
                        if (retrofitHelper == null) {
                            retrofitHelper = new RetrofitHelper();
                        }
                    }
                }
                return retrofitHelper;
            }
            
        
            private OkHttpClient getOkHttpClient() {
                // 定制OkHttp
                OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
                // OkHttp进行添加拦截器loggingInterceptor
                if (BuildConfig.DEBUG) {
                    httpClientBuilder.addInterceptor(getHttpLoggingInterceptor());
        //            httpClientBuilder.addNetworkInterceptor(new LoggingInterceptor());
                }
                httpClientBuilder.connectTimeout(20, TimeUnit.SECONDS)
                        .writeTimeout(20, TimeUnit.SECONDS)
                        .readTimeout(20, TimeUnit.SECONDS)
                        .retryOnConnectionFailure(true);
                return httpClientBuilder.build();
            }
        
            private HttpLoggingInterceptor getHttpLoggingInterceptor() {
                HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(
                        new HttpLoggingInterceptor.Logger() {
                            @Override
                            public void log(String message) {
                                Log.v("HttpInterceptor==", message);
                            }
                        });
                loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                return loggingInterceptor;
            }
        
            public void getAppCategory(final Callback<AppCategoryBean> callback){
                ApiService apiService = retrofit.create(ApiService.class);
                Call<AppCategoryBean> categoryCall = apiService.getCategory();
                categoryCall.enqueue(new Callback<AppCategoryBean>() {
                    @Override
                    public void onResponse(Call<AppCategoryBean> call, Response<AppCategoryBean> response) {
                        callback.onResponse(call,response);
                    }
        
                    @Override
                    public void onFailure(Call<AppCategoryBean> call, Throwable t) {
                        callback.onFailure(call,t);
                    }
                });
        
            }
        
        }
    

    使用缓存

    RxCache==> 使用方法

    使用retrofit的封装(Kotlin)

        val retrofitHelper = RetrofitHelper.getInstance()
        retrofitHelper.getAppCategory(object :Callback<AppCategoryBean> {
            override fun onFailure(call: Call<AppCategoryBean>, t: Throwable) {
                LogUtils.e(t.message)
            }
    
            override fun onResponse(call: Call<AppCategoryBean>, response: Response<AppCategoryBean>) {
                tv_content.text = response.body().toString()
            }
        })

    相关文章

      网友评论

          本文标题:Retrofit的简单封装

          本文链接:https://www.haomeiwen.com/subject/tegxyqtx.html