➜ RetrofitClient
Cómo implementar RetrofitClient en Android | Cómo implementar RetrofitClient en Android
Voy a programar la clase RetrofitClient para nuestra aplicación Android, la cual simplemente va a gestionar las peticiones HTTP hacia el servidor web y obtener respuestas.
En esta clase detallo las siguientes actividades:
- Declaró una variable de tipo String: para almacenar la ruta principal de la API
- Luego creamos un método llamado getRetrofit(): quién procesa la petición devolviendo un Objecto JSON
- Finalmente creo un método llamado ApiService(): el cual va a crear la instancia de ApiService para poder usar en las secciones que necesitemos en nuestra aplicación Android.
package codea.app.pizzeria9.utils;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
private static final String BASE_URL = "http://192.168.1.36/pizzeria9/public/api/";
private static Retrofit retrofit;
private static Retrofit getRetrofit(){
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
public static ApiService getApiService(){
ApiService apiService = getRetrofit().create(ApiService.class);
return apiService;
}
}
1358 visitas
Capítulo 32 – SessionManager »
Descarga el código del proyecto
Descarga el código fuente del proyecto adquiriendo el curso completo
Comprar¡Qué aprenderás?
tooltip bs-tooltip-top bs-tooltip-end bs-tooltip-bottom bs-tooltip-start show fade tooltip-inner