Issue
I am planning to make one common service class with the use of Retrofit,
@GET
Call<ResponseBody> makeGetRequest(@Url String url);
@POST
Call<ResponseBody> makePostRequest(@Url String url, @Body RequestBody parameters);
In this code i need to pass (ResponseBody) as a dynamic JSON POJO class name , Like LoginRes
Say for Example ,
Call<LoginRes> // But this class will be dynamic
I will pass ResponseBody but that ResponseBody does not know which class i wanted to prefer.
why i want this because , after result
gson.fromJson(response, LoginRes.class);
so, after getting result from Retrofit we again need to convert to gson.fromJson.
so i wanted to pass dynamic Response as Retrofit so that it will response according to my pojo class,
I know this is working fine when i pass LoginRes instead of ResponseBody because as i already told to Response that we need that response in LoginRes.
So if i pass
Call<LoginRes> // if i pass this way its working fine no need to convert my response i can access my all properties from that LoginRes class directly.
This is my example to call a Web service.
Call<ResponseBody> call = apiService.makePostRequest("/Buyer/LoginApp", requestBody);
This is how i call the Service.
Let me know if i am unclear with explanation of my problem.
waiting for some good response and suggestions on this.
Thanks Madhav
Solution
Handle GET,POST or OTHER method Like this,
if (methodType.equalsIgnoreCase(CommonConfig.WsMethodType.GET)) {
apicall = getClient(CommonConfig.WsPrefix).create(ApiInterface.class).makeGetRequest(url + CommonConfig.getQueryString(new Gson().toJson(requestBody)), getAllHeader);
} else if (methodType.equalsIgnoreCase(CommonConfig.WsMethodType.POST)) {
apicall = getClient(CommonConfig.WsPrefix).create(ApiInterface.class).makePostRequest(url, RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(requestBody)), getAllHeader);
}
Handle Response Like this.
apicall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
}
Retrofit Code
private Retrofit getClient(String WsPrefix) {
//TODO 60 to 30 second at everywhere
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(WsPrefix)
.client(okHttpClient)
.build();
return retrofit;
}
Common Interface
interface ApiInterface {
@GET
Call<ResponseBody> makeGetRequest(@Url String url, @HeaderMap() Map<String, String> header);
@POST
Call<ResponseBody> makePostRequest(@Url String url, @Body RequestBody requestBody, @HeaderMap() Map<String, String> header);
}
ApiCallback
public interface ApiCallback {
void success(String responseData);
void failure(String responseData);
}
Answered By - Madhav Anadkat
Answer Checked By - Pedro (JavaFixing Volunteer)