Retrofit Simple Encapsulation

Keywords: Retrofit Gradle JSON

Retrofit Simple Encapsulation

In a simple period, use a demo to show:

build.gradle configuration file:

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

The first time you use Retrofit, you can copy it directly, modify the specific parameters, and use it.

Retrofit simple encapsulation requires the following four basic classes:

  1. RetrofitManager
  2. OkHttpClientManager
  3. NetApi
  4. UrlConfig

It is recommended to place in the config package.

RetrofitManager class:

/**
 * @author lwj
 * @date 2017/12/15
 */

public class RetrofitManager {
    private static Retrofit.Builder sInstance;

    private static Retrofit.Builder getInstance() {
        if (sInstance == null) {
            synchronized (RetrofitManager.class) {
                if (sInstance == null) {
                    sInstance = new Retrofit.Builder();
                }
            }
        }
        return sInstance;
    }

    private static Retrofit getRetrofit(String url) {
        Retrofit retrofit = RetrofitManager.getInstance()
                // Processed okHttpClient
                .client(OkHttpClientManager.getInstance().okHttpClient)
                // Add a conversion plant.
                .addConverterFactory(GsonConverterFactory.create())
                // Add Callback Adapter Factory
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                // So far: host+port===>baseUrl
                .baseUrl(url)
                .build();
        return retrofit;
    }

    public static Retrofit getHost() {
        return RetrofitManager.getRetrofit(UrlConfig.HOST);
    }
}

OkHttpClientManager class:

/**
 * @author lwj
 * @date 2017/12/15
 */

public class OkHttpClientManager {
    private static final String TAG = OkHttpClientManager.class.getName();
    protected OkHttpClient okHttpClient;

    private OkHttpClientManager() {
        if (okHttpClient == null) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            // NONE BASIC HEADERS BODY four ways.
            // At the end of the debugging phase, BODY ----> NONE
            httpLoggingInterceptor.setLevel(BODY);
            OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
            // 10s connection timeout
            okHttpClientBuilder.connectTimeout(10, TimeUnit.SECONDS);
            // 5s Read Timeout
            okHttpClientBuilder.readTimeout(15, TimeUnit.SECONDS);
            okHttpClient = okHttpClientBuilder
                    .addInterceptor(new RequestInterceptor())
                    .addInterceptor(new CustomInterceptor())
                    .addInterceptor(httpLoggingInterceptor)
                    .build();
        }
    }

    public static OkHttpClientManager getInstance() {
        return HelpHolder.INSTANCE;
    }

    private static class HelpHolder {
        private static final OkHttpClientManager INSTANCE = new OkHttpClientManager();
    }

    /**
     * ********The following sections are custom, and the two Interceptor s can be written in one. *******************************
     */
    private class RequestInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            request.newBuilder()
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .method(request.method(), request.body())
                    .build();
            return chain.proceed(request);
        }
    }

    /**
     * Custom interceptors.
     */
    private class CustomInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            HttpUrl url = request.url();
            request.newBuilder().url(url).build();
            return chain.proceed(request);
        }
    }
}

NetApi class:

/**
 * @author lwj
 * @date 2017/12/15
 */

public class NetApi {

    public static HashMap<String, Object> buildBaseMap() {
        HashMap<String, Object> map = new HashMap<>();
        // Set the public parameters here.
        return map;
    }

    public static HashMap<String, Object> buildGeoHashMap(double lat, double lng) {
        HashMap<String, Object> map = buildBaseMap();
        map.put("lat", lat);
        map.put("lng", lng);
        return map;
    }

    /**
     * GEO_HASH
     *
     * @Body Get web html code
     * @QueryMap Get the json string.
     */
    public interface OnJqueryBack {
        @GET(UrlConfig.GEO_HASH)
        Observable<Object> onGeoHash(@QueryMap HashMap<String, Object> fields);
    }

    public static OnJqueryBack getJqueryBack() {
        return RetrofitManager.getHost().create(OnJqueryBack.class);
    }
}

UrlConfig class:

/**
 * @author lwj
 * @date 2017/12/15
 */

public class UrlConfig {
    /**
     * POST
     */
    public static final String HOST = "http://pvmap.pvbao.net/";
    public static final String GEO_HASH = "JqueryBack/GeoHash.ashx";
}

Finally, a reference to the call is given:

/**
 * Request geoHash interface
 */
private void invokeGeoHash(double lat, double lng) {
    HashMap<String, Object> map = NetApi.buildGeoHashMap(lat, lng);
    Observable<Object> observable = NetApi.getJqueryBack().onGeoHash(map);
    Subscription subscription = observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .filter(new Func1<Object, Boolean>() {
                @Override
                public Boolean call(Object o) {
                    return true;
                }
            })
            .subscribe(new Subscriber<Object>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    showToast(e.getMessage());
                }

                @Override
                public void onNext(Object o) {
                    // Data Callback
                }
            });
    mCompositeSubscription.add(subscription);
}

Finally, there are a few points to note:

  1. mCompositeSubscription is initialized in BaseActivity as shown below

    public class BaseActivity extends FragmentActivity {
        protected CompositeSubscription mCompositeSubscription = new CompositeSubscription();
    
        @Override
        protected void onDestroy() {
            if (mCompositeSubscription != null && !mCompositeSubscription.isUnsubscribed()) {
                // Subscribe to vs to unsubscribe.
                mCompositeSubscription.unsubscribe(); // Unsign/subscribe.
            }
            super.onDestroy();
        }
    }
    

    BaseFragment is the same.

  2. Object s in NetApi are often replaced with specific return types, such as CommonBean, which is called in onNext().

    Observable<CommonBean> onGeoHash(@QueryMap HashMap<String, Object> fields);
    

You can confide/comment on questions.

Posted by jakeklem on Mon, 04 May 2020 11:55:58 -0700