There's something about Retrofit that I'm not getting. I'm following examples on the web, but can't get it to even compile. I am able to access the data from the RESTful service via old school (i.e. HttpGet/HttpResoponse) so I know the service works. It returns a bunch of EmployeeData (as oppose to just one EmployeeData)
In the app gradle file:
dependencies {
...
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
...
}
The url for the RESTful service endpoint is:
https://com.somewhere/PhoneDirectoryService/api/Employees/
I have defined a string for the base url:
<string name="https_phone_directory_service_baseurl">https://com.somewherePhoneDirectoryService/api/</string>
Interface
public interface EmployeesService {
#GET("Employees.json") // the string in the GET is end part of the endpoint url
public Call<List<EmployeeEndpointResponse>> listEmployees();
}
Response
public class EmployeeEndpointResponse {
private List<EmployeeData> employees; // EmployeeData is a POJO
// public constructor is necessary for collections
public EmployeeEndpointResponse() {
employees = new ArrayList<EmployeeData>();
}
public static EmployeeEndpointResponse parseJSON(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Type collectionType = new TypeToken<List<EmployeeData>>(){}.getType();
Gson gson = gsonBuilder.create();
EmployeeEndpointResponse employeeEndpointResponse = gson.fromJson(response, EmployeeEndpointResponse.class);
return employeeEndpointResponse;
}
}
Get the data
public static boolean getEmployeeData(Context context) {
Resources resources = context.getResources();
URI uri = null;
try {
uri = new URI(resources.getString(R.string.https_phone_directory_service_baseurl));
}
catch (URISyntaxException exception) {
Log.e("getEmployeeData", exception.toString());
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(uri.toString())
.addConverterFactory(GsonConverterFactory.create())
.build();
Call<List<EmployeeEndpointResponse>> call = service.listEmployees();
EmployeesService service = retrofit.create(EmployeesService.class);
// this does not compile
// error: <anonymous com.somewhere.utilities.Utilities$1> is not
// abstract and does not override abstract method
// onFailure(Call<List<EmployeeEndpointResponse>>,Throwable) in Callback
call.enqueue(new Callback<List<EmployeeEndpointResponse>>() {
#Override
public void onResponse(Response<List<EmployeeEndpointResponse>> response) {
List<EmployeeEndpointResponse> myList = response.body();
// Successfull request, do something with the retrieved messages
}
#Override
public void onFailure(Throwable t) {
// Failed request.
}
});
// so I tried this which gives compile error
// retrofit2.Callback<java.util.List
// <com.somewhere.gson.EmployeeEndpointResponse>>)
// in Call cannot be applied to anonymous retrofit2.Callback
// <com.somewhere.gson.EmployeeEndpointResponse>)
call.enqueue(new Callback<EmployeeEndpointResponse>() {
#Override
public void onResponse(Call<EmployeeEndpointResponse> call, Response<EmployeeEndpointResponse> response) {
// handle response here
EmployeeEndpointResponse employeeEndpointResponse = (EmployeeEndpointResponse)response.body();
}
#Override
public void onFailure(Call<EmployeeEndpointResponse> call, Throwable t) {
}
});
}
What do I need to do?
Data looks like:
[
{"Name":"Smith, Ken J.",
"Cell":"",
"EmailAddress":"Ken.Smith#somewhere.com",
"Location":"West",
"Phone":"555-555-5555",
"Address":"PO Box 555 5555 Del Norte",
"City":"Jackson",
"State":"WY",
"Zip":"85555",
"Latitude":42.24976,
"Longitude":-107.82171},
{"Name":"Cox, Daniel B.",
"Cell":"",
"EmailAddress":"daniel.cox#somewhere.com",
"Location":"West",
"Phone":"(555) 555-5516",
etc ...}
]
Add the dependency
dependencies {
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
}
Generate the http client
private static OkHttpClient getOkHttpClient(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.NONE);
OkHttpClient okClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
return okClient;
}
Getting the data
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(YOUR_URL)
.client(getOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
EmployeesService service = retrofit.create(EmployeesService.class);
Call<EmployeeEndpointResponse> call = service.listEmployees();
call.enqueue(new Callback<EmployeeEndpointResponse>() {
#Override
public void onResponse(Call<EmployeeEndpointResponse> call, Response<EmployeeEndpointResponse> response) {
EmployeeEndpointResponse employeeEndpointResponse = response.body();
//manage your response
}
#Override
public void onFailure(Call<EmployeeEndpointResponse> call, Throwable t) {
}
});
Parsing JSON
Your POJO doesn't need any aditional methods to parse JSON. Just generate the code with GSON anotations with http://www.jsonschema2pojo.org/
Related
I have a Restful API whos return a Java Object for me. When return that object it is still empty, because the async thread is still working. How can get that response and return then to my Presenter and it directs the correct response to the view?
That is my retrofit call:
public String checkUser(final ModelUser modelUser) throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UserRetrofitAPI.BASE_SERVICE)
.addConverterFactory(GsonConverterFactory.create())
.build();
UserRetrofitAPI userRetrofitAPI = retrofit.create(UserRetrofitAPI.class);
Call<ModelUser> requestCheckUser = userRetrofitAPI.checkUser(modelUser.getUser(), modelUser.getPassword());
requestCheckUser.enqueue(new Callback<ModelUser>() {
#Override
public void onResponse(Call<ModelUser> call, retrofit2.Response<ModelUser> response) {
if(!response.isSuccessful()){
myModelUser = new ModelUser(modelUser.getUser(),modelUser.getPassword(), String.valueOf(response.code()));
} else {
ModelUser modelUserChecked = response.body();
myModelUser = modelUserChecked;
}
}
#Override
public void onFailure(Call<ModelUser> call, Throwable t) {
Exception ex = new Exception(t);
myModelUser = new ModelUser(modelUser.getUser(), modelUser.getPassword(), ex.toString());
}
});
return myModelUser.getResponse();
}
when I do this debugging, it works, by processing time.
help me?
You shouldn't return that directly.
As you mentioned Retrofit response is updated in background thread.
I would suggest to return requestCheckUser only and observe that in your Presenter
public Call<ModelUser> checkUser(final ModelUser modelUser) throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UserRetrofitAPI.BASE_SERVICE)
.addConverterFactory(GsonConverterFactory.create())
.build();
UserRetrofitAPI userRetrofitAPI = retrofit.create(UserRetrofitAPI.class);
Call<ModelUser> requestCheckUser = userRetrofitAPI.checkUser(modelUser.getUser(), modelUser.getPassword());
return requestCheckUser;
}
Observe response of that call in Presenter and perform required operations as follows
checkUser(modelUser).enqueue(new Callback<ModelUser>() {
#Override
public void onResponse(Call<ModelUser> call, retrofit2.Response<ModelUser> response) {
if(!response.isSuccessful()){
myModelUser = new ModelUser(modelUser.getUser(),modelUser.getPassword(), String.valueOf(response.code()));
} else {
ModelUser modelUserChecked = response.body();
myModelUser = modelUserChecked;
}
}
#Override
public void onFailure(Call<ModelUser> call, Throwable t) {
Exception ex = new Exception(t);
myModelUser = new ModelUser(modelUser.getUser(), modelUser.getPassword(), ex.toString());
}
});
This would be the simple option and will satisfy this use case and scope.
You can use custom Interface Listeners if you don't prefer to write observer in Presenter.
I would recommend to look into RxJava and use it with Retrofit to convert this into more maintainable code
I am creating an app using soundcloud api but I am getting error while parsing json object, I am new in this things so don't know what I am doing wrong here
Here is my interface
ScService.java
public interface SCService
{
#GET("/resolve.json?url=https://m.soundcloud.com/kshmr/sets/materia&client_id=iZIs9mchVcX5lhVRyQGGAYlNPVldzAoX")
Call<Track> getTrack();
}
Here is my model class
Track.java
public class Track
{
#SerializedName("title")
private String mTitle;
#SerializedName("stream_url")
private String mStreamUrl;
public String getTitle()
{
return mTitle;
}
public String getStreamUrl()
{
return mStreamUrl;
}
}
MainActivity.class
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Config.API_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
SCService Scservice = retrofit.create(SCService.class);
Call<Track> call = Scservice.getTrack();
call.enqueue(new Callback<Track>(){
#Override
public void onResponse(Call<Track> call, Response<Track> response)
{
// TODO: Implement this method
if(response.isSuccessful())
{
//String track = response.body().toString();
//Log.e("jsonres",track);
//gson = new GsonBuilder().create();
gson = new Gson();
Track track = gson.fromJson(response.body().toString(), Track.class);
}
#Override
public void onFailure(Call p1, Throwable p2)
{
// TODO: Implement this method
}
});
}
Here is the JSON response from api callcall
enter code here
{"kind":"track","id":399448641,"created_at":"2018/02/14 11:40:02 +0000","user_id":319295181,"duration":188726,"commentable":true,"state":"finished","original_content_size":33279566,"last_modified":"2018/03/10 17:33:18 +0000","sharing":"public","tag_list":"KSHMR \"House of Cards\" \"Sidnie Tipton\" Dharma \"Spinnin' \"","permalink":"houseofcards-mixmaster-05b","streamable":true,"embeddable_by":"all","purchase_url":"http://www.spinninrecords.com/releases/house-of-cards","purchase_title":"Download/Stream","label_id":null,"genre":"Dance & EDM","title":"KSHMR - House of Cards (Ft. Sidnie Tipton)","description":"KSHMR and Sidnie Tipton team up again, this time for the bittersweet sound of \"House of Cards\" \n\nDownload / Stream here: https://www.spinninrecords.com/releases/house-of-cards/","label_name":null,"release":null,"track_type":null,"key_signature":null,"isrc":null,"video_url":null,"bpm":null,"release_year":null,"release_month":null,"release_day":null,"original_format":"wav","license":"all-rights-reserved","uri":"https://api.soundcloud.com/tracks/399448641","user":{"id":319295181,"kind":"user","permalink":"dharmaworldwide","username":"Dharma Worldwide","last_modified":"2018/03/09 12:08:27 +0000","uri":"https://api.soundcloud.com/users/319295181","permalink_url":"http://soundcloud.com/dharmaworldwide","avatar_url":"https://i1.sndcdn.com/avatars-000324744374-jdrkyv-large.jpg"},"permalink_url":"https://soundcloud.com/dharmaworldwide/houseofcards-mixmaster-05b","artwork_url":"https://i1.sndcdn.com/artworks-000302088414-recq7g-large.jpg","stream_url":"https://api.soundcloud.com/tracks/399448641/stream","download_url":"https://api.soundcloud.com/tracks/399448641/download","playback_count":135077,"download_count":0,"favoritings_count":7351,"reposts_count":1354,"comment_count":120,"downloadable":false,"waveform_url":"https://w1.sndcdn.com/0Bcy6WpC8dzY_m.png","attachments_uri":"https://api.soundcloud.com/tracks/399448641/attachments","policy":"ALLOW","monetization_model":"NOT_APPLICABLE"}
I can't use gson.fromJson(...) method, how could I fix this?
Ps-I have pretty much changed my code.
You should do:
EDIT:
ScService.java
public interface SCService
{
#GET("users/17586135/tracks?client_id=iZIs9mchVcX5lhVRyQGGAYlNPVldzAoX")
Call<Track> getTrack();
}
MainActivity.class
Call<Track> call = Scservice.getTracks();
call.enqueue(new Callback<Track>(){
#Override
public void onResponse(Call call, Response<Track> response)
{
// Get the result
Track track = response.body();
}
#Override
public void onFailure(Call p1, Throwable p2)
{
// TODO: Implement this method
}
});
}
More here
The Gson object should be used in this way:
gson = new GsonBuilder().create();
Track track = gson.fromJson(response.body().toString(),Track.class);
I do a API call to a webserver and I get the ID back in the method onResponse.
Now I want to save this ID and return this id in the return of the method doLogin. How can I get that variable ID in the return statement?
This is my code:
public class LoginController {
public static String doLogin(String loginMail, String loginPassword) {
//Logging Retrofit
final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("###URLTOAPICALL###")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<JsonElement> call = service.doLogin(loginMail, loginPassword);
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
if (response != null) {
JSONObject obj = null;
try {
obj = new JSONObject(response.body().toString());
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject setup = null;
try {
setup = obj.getJSONObject("setup");
} catch (JSONException e) {
e.printStackTrace();
}
if(setup != null) {
try {
Setup stp = new Setup();
stp.setUserId(setup.getInt("id"));
//I WANT HERE TO SAVE MY ID
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Log.v("ERROR", t+"");
}
});
return "I WANT RETURN THAT ID HERE";
}
}
As retrofit is asynchronous don't return from method instead use interface callbacks.
public class LoginController {
public interface LoginCallbacks{
void onLogin(String id);
void onLoginFailed(Throwable error);
}
public static void doLogin(String loginMail, String loginPassword, final LoginCallbacks loginCallbacks) {
//Logging Retrofit
final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("###URLTOAPICALL###")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<JsonElement> call = service.doLogin(loginMail, loginPassword);
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
if (response != null) {
JSONObject obj = null;
try {
obj = new JSONObject(response.body().toString());
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject setup = null;
try {
setup = obj.getJSONObject("setup");
} catch (JSONException e) {
e.printStackTrace();
}
if(setup != null) {
try {
Setup stp = new Setup();
stp.setUserId(setup.getInt("id"));
//I WANT HERE TO SAVE MY ID
if (loginCallbacks != null)
loginCallbacks.onLogin(setup.getInt("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Log.v("ERROR", t+"");
if (loginCallbacks != null)
loginCallbacks.onLoginFailed(t);
}
});
}
}
Call method:
doLogin("email", "password", new LoginCallbacks() {
#Override
public void onLogin(String id) {
}
#Override
public void onLoginFailed(Throwable error) {
}
});
You can use a setter method within the onResponse method of your Retrofit call.
Take an instance where I have a global variable to hold distance between two points that I get from the Google maps distance matrix API:
String final_distance;
Here's my retrofit call:
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
// TODO Auto-generated method stub
JsonObject object = response.body();
String distance = object.get("rows").getAsJsonArray().get(0).getAsJsonObject().get("elements").getAsJsonArray().
get(0).getAsJsonObject().get("distance").getAsJsonObject().get("value").getAsString();
//The setter method to change the global variable
setDistance(distance);
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
// TODO Auto-generated method stub
}
});
This is what the setter method does:
private static void setDistance(String distance) {
final_distance = distance;
}
Since the Retrofit onResponse method is asynchronous, you will need to always first check whether the final_distance is not null before using it
While call.execute() function is synchronous it triggers app crashes on Android 4.0 or newer and you'll get NetworkOnMainThreadException. You have to do an async request initializing your global variable into a runnable thread. At your class name add Runnable implementation.Your getDataFunction() will look something like this:
public void getData(){
Call<JsonElement> call = service.doLogin(loginMail, loginPassword);
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
if (response.isSuccessful() && response != null) {
jsonObject = response.body().toString();//initialize your global variable
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Log.v("ERROR", t+"");
}
});
}
#Override
pulic void run(){
getDataFunction();
//here you can use your initialized variable
}
Now on your onCreate function create the run thread and start it.
Thread thread = new Thread(this);
thread.start();
This is the way it solved a similar problem of mine.
You can't since the Call you are requesting is async. If you want to run it in the same thread you must avoid using enqueue and use execute(). Keep in mind that you need to create a thread since you cant use Network Operations on the same thread.
You can solve it using Observables or use execute like in this case (not tested)
public static String doLogin(String loginMail, String loginPassword) {
//Logging Retrofit
final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("###URLTOAPICALL###")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<JsonElement> call = service.doLogin(loginMail, loginPassword);
try {
Response response = call.execute();
if (response.isSuccessful()) {
// do your stuff and
return yourString;
}
}catch (IOException ex) {
ex.printStackTrace();
}
}
You can call it in your activity using
new Thread(new Runnable() {
#Override
public void run() {
String var = doLogin("email", "paswsord");
}
});
Take care that if you want to update your UI you need to use
runOnUiThread();
I'm novice on using Retrofit, I want to post data as an json data with object format to server and get response from that, I tested my restful url with fake data and that work fine without any problem, but when i post data from android i get null. what i want to do? i want to post data to server and get response with this format:
public class UserLoginInformation {
private String username;
private String userUniqueId;
}
My interface:
public interface SignalRetrofitServiceProviders {
#POST("joinUserToApplication")
Call<List<UserLoginInformation>> joinUserToApplication(#Body Object data);
}
post data:
private void joinUserToApplication(String data) {
AlachiqRestFullProvider signalProvider = new AlachiqRestFullProvider();
SignalRetrofitServiceProviders signalRetrofitServiceProviders = signalProvider.getServices();
Call<List<UserLoginInformation>> call = signalRetrofitServiceProviders.joinUserToApplication(data);
call.enqueue(new Callback<List<UserLoginInformation>>() {
#Override
public void onResponse(Call<List<UserLoginInformation>> call, Response<List<UserLoginInformation>> response) {
List<UserLoginInformation> result = response.body();
final String r = new Gson().toJson(result);
}
#Override
public void onFailure(Call<List<UserLoginInformation>> call, Throwable t) {
t.printStackTrace();
Log.e("onFailure ", t.getMessage());
}
});
}
RestFull provider:
public class AlachiqRestFullProvider {
private SignalRetrofitServiceProviders signalRetrofitServiceProviders;
public AlachiqRestFullProvider() {
OkHttpClient httpClient = new OkHttpClient();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ClientSettings.ALACHIQ_WEB_BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
signalRetrofitServiceProviders = retrofit.create(SignalRetrofitServiceProviders.class);
}
public SignalRetrofitServiceProviders getServices() {
return signalRetrofitServiceProviders;
}
}
data for post:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("mobileNumber", mobileNumber);
jsonObject.put("userUniqueId", uuid);
jsonObject.put("userPhoneNumbers", phoneContacts);
startService(
new Intent(context, AlachiqRestFullWebServiceProvider.class)
.putExtra("request_type", "joinUserToApplication")
.putExtra("data", jsonObject.toString()));
} catch (JSONException e) {
e.printStackTrace();
}
server response data like with this format:
{"username":"mahdi","userUniqueId":"fwcrwcrwr23234c24"}
server side application to get data is:
Route.post('joinUserToApplication', function *(request, response) {
console.log(request._raw);
response.send({username: "mahdi", userUniqueId: "fwcrwcrwr23234c24"});
});
The POST body that is being serialized is a generic Object.
Create a POJO with the fields that you require and use a deserializer that retrofit understands
public interface SignalRetrofitServiceProviders {
#POST("joinUserToApplication")
Call<List<UserLoginInformation>> joinUserToApplication(#Body UserLoginInformation data);
}
Please note the parameter of the function is not changed to UserLoginInformation
http://square.github.io/retrofit/#restadapter-configuration
I am new to RxJava so please forgive me if this sounds too newbie :-).
As of now I have an abstract CallbackClass that implements the Retofit Callback. There I catch the Callback's "onResponse" and "onError" methods and handle various error types before finally forwarding to the custom implemented methods.
I also use this centralized class to for request/response app logging and other stuff.
For example: for specific error codes from my sever I receive a new Auth token in the response body, refresh the token and then clone.enqueue the call.
There are of course several other global behaviors to the responses from my server.
Current solution (Without Rx):
public abstract void onResponse(Call<T> call, Response<T> response, boolean isSuccess);
public abstract void onFailure(Call<T> call, Response<T> response, Throwable t, boolean isTimeout);
#Override
public void onResponse(Call<T> call, Response<T> response) {
if (_isCanceled) return;
if (response != null && !response.isSuccessful()) {
if (response.code() == "SomeCode" && retryCount < RETRY_LIMIT) {
TokenResponseModel newToken = null;
try {
newToken = new Gson().fromJson(new String(response.errorBody().bytes(), "UTF-8"), TokenResponseModel.class);
} catch (Exception e) {
e.printStackTrace();
}
SomeClass.token = newToken.token;
retryCount++;
call.clone().enqueue(this);
return;
}
}
} else {
onResponse(call, response, true);
removeFinishedRequest();
return;
}
onFailure(call, response, null, false);
removeFinishedRequest();
}
#Override
public void onFailure(Call<T> call, Throwable t) {
if (_isCanceled) return;
if (t instanceof UnknownHostException)
if (eventBus != null)
eventBus.post(new NoConnectionErrorEvent());
onFailure(call, null, t, false);
removeFinishedRequest();
}
My question is: Is there any way to have this sort of centralized response handling behavior before finally chaining (or retrying) back to the subscriber methods?
I found these 2 links which both have a nice starting point but not a concrete solution. Any help will be really appreciated.
Forcing request retry after custom API exceptions in RxJava
Retrofit 2 and RxJava error handling operators
Two links you provided are a really good starting point, which I used to construct solution to react to accidental
network errors happen sometimes due to temporary lack of network connection, or switch to low throughtput network standard, like EDGE, which causes SocketTimeoutException
server errors -> happen sometimes due to server overload
I have overriden CallAdapter.Factory to handle errors and react appropriately to them.
Import RetryWithDelayIf from the solution you found
Override CallAdapter.Factory to handle errors:
public class RxCallAdapterFactoryWithErrorHandling extends CallAdapter.Factory {
private final RxJavaCallAdapterFactory original;
public RxCallAdapterFactoryWithErrorHandling() {
original = RxJavaCallAdapterFactory.create();
}
#Override
public CallAdapter<?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
return new RxCallAdapterWrapper(retrofit, original.get(returnType, annotations, retrofit));
}
public class RxCallAdapterWrapper implements CallAdapter<Observable<?>> {
private final Retrofit retrofit;
private final CallAdapter<?> wrapped;
public RxCallAdapterWrapper(Retrofit retrofit, CallAdapter<?> wrapped) {
this.retrofit = retrofit;
this.wrapped = wrapped;
}
#Override
public Type responseType() {
return wrapped.responseType();
}
#SuppressWarnings("unchecked")
#Override
public <R> Observable<?> adapt(final Call<R> call) {
return ((Observable) wrapped.adapt(call)).onErrorResumeNext(new Func1<Throwable, Observable>() {
#Override
public Observable call(Throwable throwable) {
Throwable returnThrowable = throwable;
if (throwable instanceof HttpException) {
HttpException httpException = (HttpException) throwable;
returnThrowable = httpException;
int responseCode = httpException.response().code();
if (NetworkUtils.isClientError(responseCode)) {
returnThrowable = new HttpClientException(throwable);
}
if (NetworkUtils.isServerError(responseCode)) {
returnThrowable = new HttpServerException(throwable);
}
}
if (throwable instanceof UnknownHostException) {
returnThrowable = throwable;
}
return Observable.error(returnThrowable);
}
}).retryWhen(new RetryWithDelayIf(3, DateUtils.SECOND_IN_MILLIS, new Func1<Throwable, Boolean>() {
#Override
public Boolean call(Throwable throwable) {
return throwable instanceof HttpServerException
|| throwable instanceof SocketTimeoutException
|| throwable instanceof UnknownHostException;
}
}));
}
}
}
HttpServerException is just a custom exception.
Use it in Retrofit.Builder
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(new RxCallAdapterFactoryWithErrorHandling())
.build();
Extra: If you wish to parse errors that come from API (error that don't invoke UnknownHostException, HttpException or MalformedJsonException or etc.) you need to override Factory and use custom one during building Retrofit instance. Parse the response and check if it contains errors. If yes, then throw error and error will be handled inside the method above.
have you consider using the rxjava adapter for retrofit?
https://mvnrepository.com/artifact/com.squareup.retrofit2/adapter-rxjava/2.1.0
in your gradle file add
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
here's a interface for retrofit
public interface Service {
#GET("userauth/login?")
Observable<LoginResponse> getLogin(
#Query("v") String version,
#Query("username") String username,
#Query("password") String password);
}
and here's my implementation
Service.getLogin(
VERSION,
"username",
"password")
.subscribe(new Subscriber<LoginResponse>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(LoginResponse loginResponse) {
}
});
please note I'm using the gson converter factory to parse my response so I get an pojo (Plain Ole Java Object) returned.
See how you can do it.
Here is api call and pass Request model and response model in this.
public interface RestService {
//SEARCH_USER
#POST(SEARCH_USER_API_LINK)
Observable<SearchUserResponse> getSearchUser(#Body SearchUserRequest getSearchUserRequest);
}
This is the retrofit call,I used retrofit2
public RestService getRestService() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiConstants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.client(getOkHttpClient())
.build();
return retrofit.create(RestService.class);
}
//get OkHttp instance
#Singleton
#Provides
public OkHttpClient getOkHttpClient() {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(httpLoggingInterceptor);
builder.readTimeout(60, TimeUnit.SECONDS);
builder.connectTimeout(60, TimeUnit.SECONDS);
return builder.build();
}
This is the api call, call it in your activity.
#Inject
Scheduler mMainThread;
#Inject
Scheduler mNewThread;
//getSearchUser api method
public void getSearchUser(String user_id, String username) {
SearchUserRequest searchUserRequest = new SearchUserRequest(user_id, username);
mObjectRestService.getSearchUser(searchUserRequest).
subscribeOn(mNewThread).
observeOn(mMainThread).
subscribe(searchUserResponse -> {
Timber.e("searchUserResponse :" + searchUserResponse.getResponse().getResult());
if (isViewAttached()) {
getMvpView().hideProgress();
if (searchUserResponse.getResponse().getResult() == ApiConstants.STATUS_SUCCESS) {
} else {
}
}
}, throwable -> {
if (isViewAttached()) {
}
});
}
Hope this will help you.