Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 498
M. Adil Avatar asked May 05 '17 15:05

M. Adil


2 Answers

Using t.message() inside onFailure() reveals the mismatch in datatypes for json to model class, which causes this problem. just debug it via t.message() and change the datatype as suggested in the message, it will solve the problem.

like image 173
Jay Dangar Avatar answered Sep 30 '22 15:09

Jay Dangar


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.

like image 25
Usama Avatar answered Sep 30 '22 15:09

Usama