Retrofit is a library which is type-safe REST client for Android. Type-safe means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.
Before Reading this blog you have to read following blog to learn the basic knowledge of the Retrofit,
How to add Basic Authentication
Step 1: Make an interface,
1234567891011 public interface ApiInterface {String MOBIKUL_HOME_PAGE_DATA = "api/homepage/{customerId}";@GET(MOBIKUL_HOME_PAGE_DATA)Call<HomepageData> getHomePageData(@Header("Authorization") String authkey, @Path("customerId") String customerId);}
Step 2: Create the AuthToken
123456789 public static String getAuthToken() {byte[] data = new byte[0];try {data = (ApplicationConstant.API_USER_NAME + ":" + ApplicationConstant.API_PASSWORD).getBytes("UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return "Basic " + Base64.encodeToString(data, Base64.NO_WRAP);}
Step 3: Create the Retrofit Client,
1234567891011121314 public class RetrofitClient {private static Retrofit retrofit = null;public static Retrofit getClient(Context mContext) {if (retrofit == null) {retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();}return retrofit;}}
Step 4: Make your call,
1234567 public static void getHomePage(Context mContext, Callback<HomepageData> callback) {Call<HomepageData> call = RetrofitClient.getClient(mContext).create(ApiInterface.class).getHomePageData(Helper.getAuthToken(), AppSharedPref.getCustomerId(mContext));call.enqueue(callback);}call the Api with Basic Authorization,
1 RetrofitCalls.getHomePage(Activity.this, callback);
Thanks for reading this blog, You have any questions or problems comment below.
Happy Coding. Stay Super.