androidretrofit2

Retrofit always calling onFailure even response is 200


I am using Retrofit to call my API. I am very new to Retrofit and this is the reason why I am unable to find this error. I send a request to the API, API response is 200 OK but retrofit calls the onFailure method. My API interface is as follows:

public interface API {

    @FormUrlEncoded
    @POST("login")
    Call<Login> login(@Query("user") String email,@Query("pass") String password, @Field("device key") String deviceKey);

}

and my call is:

loginCall = MyApplication.getInstance().getAPI().login(username,password,deviceKey);
        loginCall.enqueue(new Callback<Login>() {
            @Override
            public void onResponse(Call<Login> call, Response<Login> response) {

                if(response.body() != null)
                {
                    Login login = response.body();
                    Toast.makeText(LoginActivity.this, response.body().toString(), Toast.LENGTH_LONG).show();
                    }
                }

            @Override
            public void onFailure(Call<Login> call, Throwable t) {
                Toast.makeText(LoginActivity.this, "Failsssssssss", Toast.LENGTH_LONG).show();
            }
        });

And my model class is as follows:

public class Login {
    String status;
    String Auth_Token;

    public Login(String status, String auth_Token) {
        this.status = status;
        Auth_Token = auth_Token;
    }
}

As far I understand this issue, there is a problem with my model class. My API returns two responses:

"{"status":"200","Auth_Token":"jhjsfbah71yb121t312hv"}"
"{"status":"500","Response":"Invalid Cardentials"}"

Any help would be appreciated. Thanks in advance.


Solution

  • There is a problem with your server response. Retrofit reads HTTP Status, So you have to make sure you sent it from the server. Retrofit is trying to read a response code 200 which is not available probably so it is calling on failure method.