Can someone help me understand the createService
method in below code. I need to understand what is method's parameter Class S
and the code underneath in depth
public class ServiceGenerator {
public static final String API_BASE_URL = Constant.BASE_URL;
private static OkHttpClient httpClient = new OkHttpClient();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
httpClient.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("cache-control","no-cache")
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
}
Found the answer myself. The entire createservice
method is not absolute necessity in this code and one can live without interceptor
declarations as shown below. If someone wants to set interceptor methods for httpClient
such as cache-control, authorization token
etc, one can use the complete code block to set them. The simplest version of createService is
public class ServiceGenerator {
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
}
Here "S" is a class type parameter. It is used to specify that the output type class to be same as input class. Then you can create you own api interface simply using this code in any activity/fragment
MyApiService myapiservice = ServiceGenerator.createService(MyApiServiceInterface.class)
Call<YourDataResponseClass> call = myapiService.getMyData(YourDataRequestClass);
call.enqueue ({.....remaining code})
Define your MyApiService
as below
public interface MyApiServiceInterface {
/*Base url is already defined in service generator class*/
@GET("/your/api/endpoint/")
/*YourDataResponseClass and YourDataRequestClass are
pojo object notation of your request and response json*/
YouDataResponseClass getMyData(
@Body YourDataRequestClass request
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With