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.

Introduction:

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

    //RxJava
    compile 'io.reactivex:rxjava:1.1.3'
    //RxAndroid
    compile 'io.reactivex:rxandroid:1.1.0'
    //retrofit
    compile 'com.squareup.retrofit2:retrofit:2.0.0'
    //retrofit relies on Gson
    compile 'com.squareup.retrofit2:converter-gson:2.0.0'
    //OkHttp
    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 = "https://api.douban.com/v2/movie/";
    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
                .build();

        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
                .build();

    }

    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
    addNetworkInterceptor(new
    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
        @GET("top250")
        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) {
        observable.subscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.newThread())//Subthread Access Network
                .observeOn(AndroidSchedulers.mainThread())//Callback to main thread
                .subscribe(observer);
    }
}

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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        initData();
    }

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

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

            @Override
            public void onNext(movieTopReq movieTopReq) {
                //Success
                Log.i("retrofit==222=", movieTopReq.getTitle()+"---"+movieTopReq.getCount()
                        +"---"+movieTopReq.getStart()+"---"+movieTopReq.getTotal()+"---"+movieTopReq.getSubjects());
            }
        });
    }
}

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