The Fourth Bounce of Android Network Request Framework: Introduction to Retrofit 2.0

Keywords: Retrofit JSON github network

Summary: The fourth bullet of the network request framework is not actually the encapsulation of Retrofit 2.0, but simply the introduction and use. As for encapsulation, after introducing RxJava, retrofit 2.0 and RxJava will be used together for encapsulation.

A brief introduction to Retrofit.

Retrofit is Square's open source network request framework, official address http://square.github.io/retrofit/ Updated to version 2.0, this article only introduces and uses version 2.0 briefly. Previous versions of Google. Retrofit is an Android client request Library in the form of rest (Rest's principle is to send get, post, put and delete to the uri of a resource for obtaining, creating, saving and deleting operations). Square's other open source frameworks include the Calendar Control Framework android-times-square Dependency injection framework dagger A picture loading framework Picasso Network requests okHttp And so on.

Simple Use of 2 Retrofit 2.0

1 Adding dependencies

A: Retrofit 2.0 dependencies

 compile 'com.squareup.retrofit2:retrofit:2.0.1'

b:gson Converter Dependence

compile 'com.squareup.retrofit2:converter-gson:2.0.1'

2. The Definition of url in Retrofit 2.0

a:
b:
c:
From the above three ways, we can see that in retrofit URL is a combination of baseUrl and @url. It is not difficult to see that only the second way is most in line with our usage habits. To sum up, when defining urls, baseUrl needs to end with "/" and @url does not start with "/".
Define our first Api in this format
baseUrl is: https://api.github.com/

   @GET("repos/{owner}/{repo}/contributors")
   Call<ResponseBody> contributorsBySimpleGetCal(@Path("owner") String owner, @Path("repo") String repo);

Then the overall url we splice is: https://api.github.com/repos/square/retrofit/contributors

3 Make a request

a: Building retrofit objects

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .build();

b: Building interface objects

 ApiService service = retrofit.create(ApiService.class);

c: The input parameters of the interface object call method return to the request object.

Call<ResponseBody> call=service.contributorsBySimpleGetCal("square","retrofit");

d: Execute the request with the call object returned in c (asynchronous request in example)

call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

e: In the call execution asynchronous request, a callback interface is passed in which there are two methods: a successful callback method and a failed callback method. In the successful callback method, we get a Response object. This object is the data we need to process.
f: Cancel the request:
call.cancel();

4 Processing the returned response

In the successful method of the callback interface, we get the response object
Let's take a look at how response works:

I won't dwell on these methods to get ResponseBody by body method.

 ResponseBody responseBody=response.body();

Let's see what responseBody does.

The method shown by the arrow in the picture shows that byte arrays can be obtained by responseBody's byte method. The byteStream method can get the input stream contentType and the most important string method for multimedia resources. Through these methods, we can see that retrofit not only supports the acquisition of json strings, but also supports the operation of multimedia files and the operation of files.
Get strings with string method

String json=responseBody.string();

In this case, we need to convert JSON characters into java objects. The common processing tools are Gson Alibaba's fast Json recommended by Google and json. Some people must think that since there are a series of transformation methods to convert JSON strings, why retrofit does not directly convert JSON strings into java objects and return them to us. Yes, retrofit 2.0 provides such an operation to add a Gson converter when building retrofit

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .**addConverterFactory(GsonConverterFactory.create())**
                .build();

Now that retrofit is going to help us convert json strings, we need to go to the type that needs to be converted and modify our api to pass in the type when defining the interface

@GET("repos/{owner}/{repo}/contributors")
    Call<List<Contributor>> contributorsBySimpleGetCal2(@Path("owner") String owner, @Path("repo") String repo);

Now let's look at how our callback interface is handled in a successful way.

 ArrayList<Contributor> contributorsList = (ArrayList<Contributor>) response.body();

This makes the procedure much simpler.

5 Add Logging for retrofit 2.0

There is no log function in retrofit 2.0, but because retrofit 2.0 relies on okHttp, we can add log function through okHttp's interceptor function.

        //Construction Log Interceptor
        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //Construct OkHttpClient and set up interceptor
        OkHttpClient client=new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();
        //Construct retrofit and set OKHttpClient
        Retrofit retrofit=new Retrofit.Builder()
                .client(client)
                .baseUrl("https://api.github.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

As a result, log functionality has been successfully added as follows

6 Adding request headers for retrofit requests

a: Use annotations to add request headers to the Api interface
Since retrofit 2.0 is so powerful, there must be an operation on the request Header.

We can see that there are two ways.
Header adds one at a time

 Call<List<Contributor>> contributorsBySimpleGetCal3(@Header("name") String name, @Path("owner") String owner, @Path("repo") String repo);

Headers add more than one at a time

    @Headers({
            "Accept: application/vnd.github.v3.full+json",
            "User-Agent: Retrofit-Sample-App"
    })
    @GET("repos/{owner}/{repo}/contributors")
    Call<List<Contributor>> contributorsBySimpleGetCal3( @Path("owner") String owner, @Path("repo") String repo);

b: Use okHttp3 to add interceptors to set request headers when building OKHttpClient

//Construct OkHttpClient and set up interceptor
        OkHttpClient client=new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request request=chain.request().newBuilder()
                                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                                .addHeader("Accept-Encoding", "gzip, deflate")
                                .addHeader("Connection", "keep-alive")
                                .addHeader("Accept", "*/*")
                                .addHeader("Cookie", "add cookies here")
                                .build();
                        return chain.proceed(request);
                    }
                })
                .addInterceptor(loggingInterceptor)
                .build();

Three summary

Today, I've brought you an introduction to Retrofit 2.0. In fact, nothing is simple introduction and use. This paper refers to Li Jiangdong's Retrofit 2.0 Usage Details Reference to the days spent online Retrofit 2.0: The biggest improvement ever Here I express my deep gratitude.

Posted by Rose.S on Fri, 12 Apr 2019 22:51:32 -0700