Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android successful JSON response but response.isSuccess() is not true

I am finally getting a response from the Instagram's API for the access token.

final Call<TokenResponse> accessToken =  ServiceManager.createTokenService().getAccessToken(request);
accessToken.enqueue(new Callback<TokenResponse>() {
    @Override
    public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
        mtext.setText("hello");
      }

    @Override
    public void onFailure(Call<TokenResponse> call, Throwable t) {
        mtext.setText("failure");
    }
});

However when I check if response.isSuccess() it fails? I don't understand this.

Also, I am using Retrofit 2 and I have imported the Gson should it automatically map the data right?

like image 435
Hasan Nagaria Avatar asked Jan 06 '23 14:01

Hasan Nagaria


1 Answers

In retrofit 2, onFailure only invoked when a network or unexpected exception occurred during the HTTP request.

response.isSuccess() when the http status is 2xx or 3xx it will return true, or else, it will return false.

So, when isSuccess is true, you can use right data model to map the json. You can define a common error model to map the json when isSuccess is false.

[EDIT]Add some smaple code snippet that I used retrofit2 in my project, hope this will help you.

@Override public void onResponse(Response<T> response, Retrofit retrofit) {
  onNetworkRequestFinished();
  if (response.isSuccess()) {
    onSuccess(response.body());
  } else {
    onFailed(response, retrofit);
  }
 }


@Override public void onSuccess(SignupResponse signupResponse) {
  ((JFragmentActivity) context).dialogHelper.dismissProgressDialog();
  sharedPreferenceHelper.saveLoginName(context, userName); 
  doAfterSignin(context, signupResponse);
}


public void onFailed(Response response, Retrofit retrofit) {
  Converter<ResponseBody, JErrorReponse> errorConverter =
    retrofit.responseConverter(JErrorReponse.class, new Annotation[0]);

    try {
      JErrorReponse error = errorConverter.convert(response.errorBody());
      if (error != null) {
        JToast.toastLong(error.msg);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

the JErrorResponse.java

public class JErrorReponse implements Serializable {
  public int status;
  public String msg;
  public Object err;
}

SignupResponse.java

public class SignupResponse extends BaseResponse {

  public UserLoginData data;
}

UserLoginData.java

public class UserLoginData implements Serializable {
  @SerializedName("u_id") public int uId;

  @SerializedName("username") public String userName;

  public String icon;
}
like image 119
Weibo Avatar answered Feb 15 '23 23:02

Weibo