Recently, I have finished my work at hand, so I am thinking of doing some optimization. Seeing that the previous set of network framework used to add a request is more troublesome, and more difficult to use, so I want to transform the network framework. 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. This article is a brief introduction to the basic use of Retrofit. Retrofit + RxJava + OkHttp encapsulation will be written later. The following is the text.

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.

One, Retrofit writes a web request

Take douban Top250 list as an example, api.douban.com/v2/movie/

1. First, to use Retrofit, you definitely need to import its package, add the following configuration to your build.gradle file:

The compile 'com. Squareup. Retrofit2: retrofit: 2.1.0' / / retrofit the compile 'com. Google. Code. Gson: gson: 2.6.2' / / gson library / / the following are RxJava and RxAndroid compile 'IO. Reactivex: RxJava: 1.1.0' compile 'IO. Reactivex: RxAndroid: 1.1.0' compile 'com. Squareup. Retrofit2: converter - gson: 2.1.0' / / converter, Request the results into the Model the compile 'com. Squareup. Retrofit2: adapter - rxjava: 2.1.0' / / cooperate rxjava useCopy the code

2. Create an instance of Retrofit and complete the configuration

public static final String BASE_URL = "https://api.douban.com/v2/movie/";
Retrofit retrofit = new Retrofit.Builder() 
       .baseUrl(BASE_URL) 
       .addConverterFactory(GsonConverterFactory.create())
       .build();Copy the code

Description: configure the interface baseUrl and a converter, GsonConverterFactory is provided in the default Gson converter, Retrofit also support other converter, details please see website Retrofit website

Create an interface as follows:

Public interface MovieService {// GET(" Top250 ") Call getTop250(@query ("start") int start,@Query("count")int count); }Copy the code

Description: GetTop250 defines a method, using the get request, add @ get label, the label is followed by the interface end address top250, full address should be the baseUrl + tail address parameters using the @ Query tags, if can use @ QueryMap parameters more labels, Receiving a Map

4. Create interface instance MoiveService with Retrofit and call the method in the interface for network request, code as follows:

MovieService MovieService = retrofit.create(MovieService. Class); // Call the method to get a Call Call Call = movieService. GetTop250 (0,20); Call. Enqueue (new Callback() {@override public void onResponse(call, Callback); Response response) { mMovieAdapter.setMovies(response.body().subjects); mMovieAdapter.notifyDataSetChanged(); } @Override public void onFailure(Call call, Throwable t) { t.printStackTrace(); }});Copy the code

Execute () returns a Response as follows:

Response response = call.execute();Copy the code

This is an online request from Retrofit to get the top250 movies on douban:




84193B9F-BBAE-4967-ADB4-F923A422AD64.png

The above example is done using get. To use POST, we just need to modify the method definition in the interface as follows:

Public interface MovieService {// getTop250 @formurlencoded @post (" Top250 ") Call getTop250(@field ("start") int start, @Field("count") int count); }Copy the code

Note: When using POST, you only need to change the method definition tag, use @POST tag, and use @field or @body or FieldMap for parameter tags. Note: When using POST, you must add @Formurlencoded tag, otherwise an exception will be thrown. 2, use POST mode, must have parameters, otherwise will throw exception, source exception is as follows:

if (isFormEncoded && ! gotField) { throw methodError("Form-encoded method must contain at least one @Field."); }Copy the code

This is a complete example of using Retrofit to complete a web request. See the website for other ways to use tagsRetrofit websiteThe usage on the official website is also introduced in detail. In addition, I found a blog that also introduced in detail.A detailed explanation of how to Retrofit

Two, use with RxJava

1, change the interface defined so that instead of returning a Call, an Observble is returned.

Public interface MovieService {// GET(" Top250 ") Observable getTop250(@query ("start") int start, @Query("count")int count); }Copy the code

2. Add the following code when creating Retrofit

addCallAdapterFactory(RxJavaCallAdapterFactory.create())Copy the code

3, Add Converter to Converter(convert JSON to JavaBean)

addConverterFactory(GsonConverterFactory.create())Copy the code

4. Pass Subscriber in the Activity or Fragment to establish a subscription relationship

Subscription = movieService. GetTop250 (0,20). SubscribeOn (schedulers.io ()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(MovieSubject movieSubject) { mMovieAdapter.setMovies(movieSubject.subjects); mMovieAdapter.notifyDataSetChanged(); }});Copy the code

The above is the network request after adding RxJava. The return is no longer a Call, but an Observable. If a Subscriber is passed in the Activity/Fragment to establish a subscription relationship, the result can be processed in onNext. The nice thing about RxJava is that it helps me handle switching between threads, so we can specify which thread the subscription is on and observe which thread. We can transform data through operators. The whole process is chained, simplifying the logic. The FlatMap operator can also solve the problem of multi-layer nesting. All in all, RxJava is very powerful and can help me deal with a lot of complex scenarios, which can improve our development efficiency if we use it skillfully. I’m not going to cover RxJava here, but if you don’t know RxJava, or if you’re not familiar with RxJava, I recommend a few well-written blogs.

1, RxJava classic article, throw line for Android developers RxJava details 2, about RxJava friendly article 3, about RxJava friendly article – advanced

Add the OkHttp configuration

OkHttpClient allows you to configure many things, such as link timeouts, caches, interceptors, and more. The code is as follows:

// create okHttpClient.builder Builder = new okHttpClient.builder (); builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS); WriteTimeout (DEFAULT_TIME_OUT, timeunit.seconds); // Connection timeout builder.writeTimeout(DEFAULT_TIME_OUT, timeunit.seconds); // Write timeout builder.readTimeout(DEFAULT_TIME_OUT, timeunit.seconds); / / / / read timeout time add public parameters interceptor BasicParamsInterceptor BasicParamsInterceptor = new BasicParamsInterceptor. Builder () .addHeaderParam("userName","")// Add a public argument.addHeaderParam("device","").build(); builder.addInterceptor(basicParamsInterceptor); MRetrofit = new retrofit.builder ().client(builder.build()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(ApiConfig.BASE_URL) .build();Copy the code

In a real project, we might have some common parameters, such as device information, channel, Token, etc., which are required for each interface. We could write an interceptor and configure it into OKHttpClient. AddInterceptor (basicParamsInterceptor) so we don’t have to add these parameters to every interface. Caching can also be implemented by writing an interceptor (more on that later).

That’s a simple example of Retrofit+RxJava+OkHttp implementing network requests, and it would be too much code and not elegant to write it this way for every interface. So we also need to encapsulate, because space is limited, encapsulate in the next article.

Retrofit + RxJava + OkHttp packaging has been updated, please seeRetrofit + RxJava + OkHttp makes web requests simple – encapsulation

Refer to the blog: 1, Detailed usage of Retrofit 2, Based on Retrofit, OkHttp, Gson encapsulation of the general web framework 3, RxJava combined with Retrofit best practices