Creating an API service

We explained this procedure in Chapter 4, Spring Modules for Android. So we will just show you the code and explain the new features. Create an object named APIService.kt and add gsonConverter() and getOkhttpClient(username, password):

object APIService{
fun getRetrofitBuilder(username:String, password:String): Retrofit {
return Retrofit.Builder()
.client(getOkhttpClient(username, password))
.baseUrl(Constants.API_BASE_PATH)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(gsonConverter())
.build()
}

fun gsonConverter(): GsonConverterFactory {
return GsonConverterFactory
.create(
GsonBuilder()
.setLenient()
.disableHtmlEscaping()
.create()
)
}

fun getOkhttpClient(profileName: String, password: String): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(BasicAuthInterceptor(profileName, password))
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build()
}
}

If you're confused about addInterceptor(BasicAuthInterceptor(profileName, password)), then please go to Chapter 5, Securing Applications with Spring Security, and check out the section called Authenticating with OkHttp interceptors

Now we need to initialize the RetrofitBuilder functions of the services. We have four service interfaces, and now we will create four RetrofitBuilder functions for them. Add this code in the APIService.kt file:

// get profile request builder
fun profileAPICall(username:String, password:String) = getRetrofitBuilder(username, password)
.create(ProfileService::class.java)

// get post request builder
fun postAPICall(username:String, password:String) = getRetrofitBuilder(username, password)
.create(PostService::class.java)

// get comment request builder
fun commentAPICall(username:String, password:String) = getRetrofitBuilder(username, password)
.create(CommentService::class.java)

Now we will work for the frontend, which means the activities and layouts. 

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

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