Service factory

Let's start by creating a class--RetrofitYahooServiceFactory:

public class RetrofitYahooServiceFactory {
}

Before we can make our first request, we will need to prepare an interceptor that we will use for logging:

public class RetrofitYahooServiceFactory {

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY);
}

It is advised to turn off logging for production applications to get better performance but, in our case, especially while we are learning, it is crucial to have appropriate logging so that we can see what is actually going on.

Afterward, the OkHttp client that the Retrofit will use, can be prepared:

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

The Retrofit object will be constructed by calling the following:

Retrofit retrofit = new Retrofit.Builder()
.client(client)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://query.yahooapis.com/v1/public/")
.build();

Here, a few things need our attention.

The .client(client) sets the actual HTTP client that we will be using. In this case,it's OkHttp.

By calling .addCallAdapterFactory() and using RxJava2CallAdapterFactory we integrate RxJava compatibility into Retrofit library.

The .addConverterFactory() call along with GsonConverterFactory adds support for JSON response parsing into Java objects.

Finally, we can set the root URL of our service that we will be using with .baseUrl(). This part sets the last missing part of the URL that we took as an example.

There are a few ways to choose baseUrl and the structure of Retrofit calls but, for the sake of simplicity, we will leave it as it is here in the example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.146.155