Of course, Retrofit+RxJava + OkHttp is very popular on Android market. It is powerful and easy to use, so this solution is chosen to transform the network library.

Brief introduction:

Retrofit: Retrofit is a framework developed by Square for Android web requests. The underlying implementation is based on OkHttp, which has been officially approved by Google. Retrofit website

OkHttp: Also Square’s open source web request library

RxJava – “A library for composing Asynchronous and Event-based programs using Observable” on GitHub Sequences for the Java VM” (a library that uses observable sequences on the Java VM to compose asynchronous, event-based programs). This is RxJava, and it’s summed up very precisely. In short, it makes asynchronous operations very simple.

Respective responsibilities: Retrofit is responsible for the requested data and the results of the request, rendered using an interface, OkHttp is responsible for the process of the request, and RxJava is responsible for asynchronous, switching between various threads.

RxJava + Retrofit + okHttp has become the most popular method for Android web requests.

Add a dependency library

    //RxJava
    compile 'the IO. Reactivex: rxjava: 1.1.3'
    //RxAndroid
    compile 'the 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'
Copy the code

Generate interface instance management class

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 time.writeTimeout (DEFAULT_WRITE_TIME, Timeunit.seconds)// set the write timeout time. readTimeout(DEFAULT_READ_TIME, timeunit.seconds)// set the readTimeout time. build(); Retrofit = new retrofit.builder ().client(okHttpClient)// Set to use the okHTTP network request.baseurl (REQUEST_PATH)// set the server path AddConverterFactory (GsonConverterFactory. The create ()) / / add into library, Default is Gson. AddCallAdapterFactory (RxJavaCallAdapterFactory. The create ()) / / add the callback library, using RxJava. The build (); } private static class SingletonHolder { private static final RetrofitServiceManager INSTANCE = new RetrofitServiceManager(); } /* * RetrofitServiceManager ** public static RetrofitServiceManagergetInstance() {
        return SingletonHolder.INSTANCE;
    }

    public <T> T create(Class<T> service) {
        returnretrofit.create(service); }}Copy the code

After upgrading from Retrofit to 2.0, the Build design pattern (producer pattern) was used to separate a complex build from its presentation. Build design mode is also used after upgrading to OKHttp3.

CookieJar (new CookiesManager()) : addInterceptor(new MyIntercepter()) : Add an interceptor addNetworkInterceptor (new CookiesInterceptor (MyApplication. GetInstance (). GetApplicationContext ())) : Add a network connector connectTimeout(30, timeunit.seconds): request timeout time writeTimeout(30, timeunit.seconds): writeTimeout timereadTimeout(30, timeUnit. SECONDS): read Timeout periodCopy the code

Create an interface class

Public interface MovieService {// GET top 20 list @get ("top250")
        Observable<movieTopReq> getMovicTop(@Query("start") int start, @Query("count") int count);
    }
Copy the code

The interface is already created, Retrofit is set up with annotations, the URL to access, how the request is made, the request header. @get, @post, @query, @header, used to add Header headers, @formurlencoded POST Header, etc. @PUT means this is a PUT request @DELETE means this is a DELETE request @HEAD means this is a HEAD request @OPTIONS means this is an OPTION request @PATCH means this is a PAT request

Create an implementation interface to facilitate invocation

public class HttpEngine { private static MovieService movieService = RetrofitServiceManager.getInstance().create(MovieService.class); Public static void getDuoBanTop(int start, int count, Observer<movieTopReq> Observer) {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 ())// Child threads access the network ObserveOn (AndroidSchedulers. MainThread ()) / / callback to the main thread. The subscribe (observer); }}Copy the code

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. Activity invocation

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() {// call the wrapped retrofit request method httpEngine.getDuobantop (0, 20, new Observer<movieTopReq>() {@override public voidonCompleted} @override public void onError(Throwable e) {"retrofit==111="."Request error:"+e.getMessage()); } @override public void onNext(movieTopReq movieTopReq) {"retrofit==222=", movieTopReq.getTitle()+"-"+movieTopReq.getCount()
                        +"-"+movieTopReq.getStart()+"-"+movieTopReq.getTotal()+"-"+movieTopReq.getSubjects()); }}); }}Copy the code

Need a Demo of children’s shoes public account reply: “Retrofit” can be obtained


The following is our personal public account (LongXuanzhigu). Our articles will be synchronized to this account, which is convenient for exchanging and learning Android knowledge and sharing personal favorite articles: