Webservices Api Calling Using Retrofit In Common Class
Posted By : Keshav Gupta | 07-Sep-2017
OkHttp is used by retrofit for HTTP requests internally.Now I am going to explain each and every step to integrate retrofit and call apis through it using a common class for api calls.It is basically faster in response.In retrofit we can configure which converter we want to use for data serialization.So here for json we will use Gson.For implementing retrofit we need basic three things:
1) Model class which will use to map the json into it.
2) class in which interfaces are defined for all Http operations.
3) Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL end point for the HTTP operation.
Step1:Add following line in app/build.gradle to install retrofit and Gson in application
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
Step2:Create a interface class named as ApiInterface which contains interfaces for all Http operations.It will be like this.
public interface ApiInterface {
@Headers({
"Content-Type: application/x-www-form-urlencoded",
"ft_knox_auth: !4_4(8)kSH6#w(9)*tzfVvo:-t%j{(6)WC6:1<$>"
})
@FormUrlEncoded
@POST("patient-register")
Call<SignUpBean> postSignUpResp(@Field("email") String email,
@Field("password") String password,
@Field("mobile") String mobile,
@Field("name") String name);
@Headers({
"Content-Type: application/x-www-form-urlencoded",
"ft_knox_auth: !4_4(8)kSH6#w(9)*tzfVvo:-t%j{(6)WC6:1<$>"
})
@FormUrlEncoded
@POST("patient-login")
Call<LoginBean> postLoginResponse(@Field("userlogin") String userlogin,
@Field("password") String password);
}
Step3:Create a RetrofitBuilder class named as ApiClient which uses the interface and the Builder API which allows defining the URL end point for the HTTP operation.
public class ApiClient {
public static final String BASE_URL =”YOUR BASE URL”;
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Step4: Create a class named as AppConstant which contain requestcode for every call which will be used in interface callback on fragment and activity to identify which service call result is in success or failure at current instant.It will be like.
public class AppConstant {
public static final int LOGIN_REQUEST = 1;
public static final int SIGNUP_REQUEST = 2;
public static final int OTP_REQUEST = 2;
public static final int PROFILE_REQUEST = 3;
public static final int ADD_DISEASE_SYMPTOM = 4;
}
Step5:Create a interface class named as ApiResponseInterface which will be having two methods declared one for success and one for failure.It will be like.
public interface ApiResponseInterface {
public void isError(String errorCode);
public void isSuccess(Object response, int ServiceCode);
}
Step6:Create a class named as ApiManager which contain method for all types of api calls.It will be like.
public class ApiManager {
private Context mContext;
private ProgressDialog dialog;
private ApiResponseInterface mApiResponseInterface;
public ApiManager(Context context, ApiResponseInterface apiResponseInterface) {
this.mContext = context;
this.mApiResponseInterface = apiResponseInterface;
dialog = new ProgressDialog(mContext);
}
/**
* The purpose of this method is to make the login request to the server
*
* @param mobStr
* @param passwordStr
*/
public void makeLoginRequest(String mobStr, String passwordStr) {
showDialog("Login user...");
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<LoginBean> call = apiService.postLoginResponse(mobStr, passwordStr);
call.enqueue(new Callback<LoginBean>() {
@Override
public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
closeDialog();
if (response.body().getACK().equalsIgnoreCase("success")) {
mApiResponseInterface.isSuccess(response.body(), AppConstant.LOGIN_REQUEST);
} else {
mApiResponseInterface.isError(response.body().getMessage());
}
}
@Override
public void onFailure(Call<LoginBean> call, Throwable t) {
closeDialog();
Toast.makeText(mContext, "Network Error", Toast.LENGTH_LONG).show();
}
});
}
/**
* The purpose of this method is to make the registration request to the server
*
* @param mobStr
* @param passwordStr
* @param emailStr
* @param fullNameStr
*/
public void makeRegistrationRequest(String emailStr, String passwordStr, String mobStr, String fullNameStr) {
showDialog("Register user...");
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<SignUpBean> call = apiService.postSignUpResp(emailStr, passwordStr, mobStr, fullNameStr);
call.enqueue(new Callback<SignUpBean>() {
@Override
public void onResponse(Call<SignUpBean> call, Response<SignUpBean> response) {
closeDialog();
if (response.body().getACK().equalsIgnoreCase("success")) {
mApiResponseInterface.isSuccess(response.body(),AppConstant.SIGNUP_REQUEST
);
} else {
mApiResponseInterface.isError(response.body().getMessage());
}
}
@Override
public void onFailure(Call<SignUpBean> call, Throwable t) {
closeDialog();
Toast.makeText(mContext, "Network Error", Toast.LENGTH_LONG).show();
}
});
}
/**
* The purpose of this method is to show the dialog
*
* @param message
*/
private void showDialog(String message) {
dialog.setMessage(message);
dialog.show();
}
/**
* The purpose of this method is to close the dialog
*/
private void closeDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}
Now user has to finally interact with this class and get response like this.In your activity or fragment class.What you have to do is like this:
1) Declare the object for interface class and manager class
private ApiManager mApiManager;
private ApiResponseInterface mInterFace;
2) We created a method to setup whole structure named as setUpNetwork which contains instantiation for interface class and its overrided method which will capture response from interfaces including requestcode.Like this.
/**
* The purpose of this method is to setup the network and and handle the responses
*/
private void setupNetwork() {
mInterFace = new ApiResponseInterface() {
@Override
public void isError(String errorCode) {
Toast.makeText(mActivity, errorCode, Toast.LENGTH_SHORT).show();
}
@Override
public void isSuccess(Object response, int ServiceCode) {
if (ServiceCode == AppConstant.LOGIN_REQUEST) {
LoginBean loginBean = (LoginBean) response;
} else if (ServiceCode == AppConstant.OTP_REQUEST) {
OtpRequestBean otpRequestBean = (OtpRequestBean) response;
}
}
};
mApiManager = new ApiManager(this, mInterFace);
}
3)Above all setup was to how to setUp callback in container class.Now we will get to know about how to call api.We will call suitable method using apimanager instance.Call will be like this.
mApiManager.makeLoginRequest(mobStr, passwordStr);
In after this login call is processed in ApiManager Class which onSuccess or onError pushes the result to interface.In above strucure in ApiManager class there can be more methods you can create as of need.So all calls are utilized from a common class.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Keshav Gupta
Keshav Gupta is Android Developer in Oodles, he always look forward for new tasks and new things to learn more.