Android encapsulates Retrofit2+OkHttp3+RxJava network requests

Now, Retrofit+RxJava+OkHttp is the most popular option in Android market. It is powerful and easy to use, so this solution is chosen to transform the network library.


Retrofit: Retrofit is a framework developed by Square Corporation that is requesting Android networks.The underlying implementation is based on OkHttp, which has been officially recognized by google.Retrofit Official

OkHttp: is also an open source network request library for Square

RxJava:RxJava's self-introduction on the GitHub home page is "a library for composing asynchronous and event-based programs using observable sequences for the Java VM" (a library for asynchronous, event-based programs using observable sequences on Java VM).This is RxJava, which is a very precise summary.All in all, it makes the asynchronous operation very simple.

Their respective responsibilities: Retrofit is responsible for the data requested and the result of the request, presents it using the interface, OkHttp is responsible for the request process, RxJava is responsible for asynchronous, and switches between threads.

RxJava + Retrofit + okHttp has become the most popular way for Android network requests.

1. Add Dependent Libraries

    compile 'io.reactivex:rxjava:1.1.3'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.squareup.retrofit2:retrofit:2.0.0'
    //retrofit relies on Gson
    compile 'com.squareup.retrofit2:converter-gson:2.0.0'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    //retrofit relies on RxJava
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'

2. Management Class for Generating Interface Instances

public class RetrofitServiceManager {
    private static final int DEFAULT_CONNECT_TIME = 10;
    private static final int DEFAULT_WRITE_TIME = 30;
    private static final int DEFAULT_READ_TIME = 30;
    private final OkHttpClient okHttpClient;
    private static final String REQUEST_PATH = "";
    private final Retrofit retrofit;

    private RetrofitServiceManager() {

        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_CONNECT_TIME, TimeUnit.SECONDS)//Connection timeout
                .writeTimeout(DEFAULT_WRITE_TIME, TimeUnit.SECONDS)//Set write operation timeout
                .readTimeout(DEFAULT_READ_TIME, TimeUnit.SECONDS)//Set read operation timeout

        retrofit = new Retrofit.Builder()
                .client(okHttpClient)//Set up network requests using okhttp
                .baseUrl(REQUEST_PATH)//Set Server Path
                .addConverterFactory(GsonConverterFactory.create())//Add transformation library, default is Gson
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//Add callback library using RxJava


    private static class SingletonHolder {
        private static final RetrofitServiceManager INSTANCE = new RetrofitServiceManager();

    * Get RetrofitServiceManager
    public static RetrofitServiceManager getInstance() {
        return SingletonHolder.INSTANCE;

    public <T> T create(Class<T> service) {
        return retrofit.create(service);

After Retrofit was upgraded to 2.0, the build design mode (producer mode) was used to separate a complex build from its representation.
build design mode is also used when upgrading to okhttp3.

okhttp Parameter description:
    cookieJar(new CookiesManager()):  Set up an automatic management cookies Manager
    addInterceptor(new MyIntercepter()): Add Interceptor
    CookiesInterceptor(MyApplication.getInstance().getApplicationContext())): Add Network Connector
    connectTimeout(30, TimeUnit.SECONDS):Request Timeout 
    writeTimeout(30,TimeUnit.SECONDS):Write Timeout 
    readTimeout(30, TimeUnit.SECONDS):Read Timeout

3. Creating interface classes

public interface MovieService {
        //Get Top 20 Bean Flaps
        Observable<movieTopReq> getMovicTop(@Query("start") int start, @Query("count") int count);

The interface has been created and Retrofit is set up with comments, the url to be accessed, the request method, and the request header.
Common Notes:
@GET GET Request Method
@POST POST Request Method
@Query GET request parameters
@Header is used to add a Header request header
@FormUrlEncoded post request header tag
Other ways to request comments:
@PUT indicates that this is a PUT request
@DELETE indicates that this is a DELETE request
@HEAD indicates that this is a HEAD request
@OPTIONS indicates that this is an OPTIONS request
@PATCH indicates that this is a PAT request

4. Create implementation interfaces to facilitate calls

public class HttpEngine {

    private static MovieService movieService = RetrofitServiceManager.getInstance().create(MovieService.class);

    * Get Douban Movie List
    * **/
    public static void getDuoBanTop(int start, int count, Observer<movieTopReq> observer) {
        setSubscribe(movieService.getMovicTop(start, count), observer);

    private static <T> void setSubscribe(Observable<T> observable, Observer<T> observer) {
                .subscribeOn(Schedulers.newThread())//Subthread Access Network
                .observeOn(AndroidSchedulers.mainThread())//Callback to main thread

Unify the network interfaces into an interface class and let Retrofit create implementation interfaces for easy invocation.The setSubscribe method is essentially inserting an observer.

5. Actity Calls

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;

    protected void onCreate(Bundle savedInstanceState) {

    private void initData() {
        //Invoke wrapped retrofit request method
        HttpEngine.getDuoBanTop(0, 20, new Observer<movieTopReq>() {
            public void onCompleted() {

            public void onError(Throwable e) {
                Log.i("retrofit==111=", "Request error:"+e.getMessage());

            public void onNext(movieTopReq movieTopReq) {
                Log.i("retrofit==222=", movieTopReq.getTitle()+"---"+movieTopReq.getCount()

Public Number Response for Child Shoes in Need of Demo:'Retrofit'is available

The following is the Personal Public Number (longxuanzhigu), which will be synchronized with the published articles to facilitate the exchange of Android knowledge and sharing of personal favorite articles:

Tags: Android Retrofit OkHttp network

Posted on Wed, 14 Aug 2019 19:09:25 -0700 by AncientSage