Ask Questions

Implementation of Retrofit on Android Project

How to implement Retrofit in Android Project for api calls

  1. First We have to implement in build.gradle(Module:app)
    // retrofit

    implementation ‘com.squareup.retrofit2:retrofit:2.1.0’
    implementation ‘com.squareup.retrofit2:converter-gson:2.1.0’

  2. Now Create class to retro client WebService.java, The following demo code is used in android studio sample project.
    import okhttp3.OkHttpClient;
    import retrofit2.Retrofit;
    import retrofit2.converter.gson.GsonConverterFactory;
    public class WebService {
    private static Retrofit retrofit = null;
    private static String BASE_URL = "http://api.xyz.com/WebAPI";
    private static String API_URL = BASE_URL+"/api/"; static Retrofit getClient() {
    // HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    // interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().build();
    retrofit = new Retrofit.Builder()
    .baseUrl(API_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();
    return retrofit;
    }
    }
    The getClient() method in the above code will be called every time while setting up a Retrofit interface. Retrofit provides with a list of annotations for each of the HTTP methods: @GET, @POST, @PUT, @DELETE, @PATCH or @HEAD.
  3. Now create Interface WebInterface.java

Leave a Reply

Your email address will not be published. Required fields are marked *