java – Retrofit 2 Response is null even when response code is 200 and response.isSuccessful() is true

My json response file is :

{
    "access_token": "3lfX6-GCJv8uWZE8h8OSDL5eY5oiiInNjLKZTy2ZFxj7Tru4Ounb3jIdPGMe48Ed6QchTGI3il3NxAOTdHe-3hc-1jAsqiCk6Jq_w5DfRESOfjqNBXQCM6sSj65ugygn8F8mIV9DxSm7Ac6GZu5rwwk-yVnYjNh_6xEReqCn21ZzvYIuZJ2M8YGa73o0CPwtGsJO9dPUPIrZAdK1c08iYyAixnG4aqpLfpUnHzmTyng_QQXp1TD3xfPhsNApDymx89BbCvNF2iDKvh75fGYfWKXOUj6QCOrdI4PH0PDU92e6Acjs3GZdyTo5a6SfKR5Pnfm_koehsNcCVG00xtVnfCcFJkVYaSJ5sfyjoCQ5aS8wgEOpPbHtk6AmxQqFBMHgVryxgEphKfriXOJmtg9MTE7CasVM7Ur6tFzf_sqUJERuQWDtGn6QowHVKoMHmM4stRqgU02i1MiiKzv_m83D1Fht1TjAna73_FICdWyXtijzJOaTEdWINclPxUmOa1CjjFcIVRFb0Xn3znTcI7AyNy2UJ_b3r7wf3MxZdR2TNxS9WGPdflIA5cswRy2nxQgex5cKj24c7s8fmaxm2eRH9nG3iGIK1MkQkEc58Wq0nQcPsUTnlRc1x6uAy8H9HToar9ndGnz8yh8XLBqe2PmBKXRIDBIBr_cEqP2vPmJDVq9-yaoJOPNJ4LHhuthTpNoMlhbin892yZHt1jZvJANAMtk8Ub5gkXsOggzzQoGMuWZYcoFVNGDkwiMmG624ija4kWnMAfoxar14OMnBxPbli1macFrfo5VDuZPzz9uoFEudwLeb-FPRsUSXxXj6lttVllOGKRG1bjX58DimfIfP6Mkk1C9w_Snij6sHHe1iY7V_mCOUQzsn1zoyLr5F9UbyoMAaARIOlVjTpZdLQwuz7dVmkQjAisUuJF01PHWyBZVSuKknWqhNivw8Y2QRJwlWGl4EOA1xFU12Qa_aPLL2BFfn-dMFZjALwEQ8-E9t3A63twjC-hx1K5X_3m04alsPFojFbF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b-9BwhlMfkv_SDVpkTortF_GZt-CBgtxhqmLANHWhRpdcqCMTEIamC_F1YIo2BxbZHbS3zXyGwIk4IUp3AObc54hw39bHkE0xxUwSHVPtZJkU4F0QrsISTy3Xg0SIVuoX6a6trN5l7d1RMrZj9EQKuW-5h1dQ-kNH5j3OVb5nzcw4GuVGjx-EuAeB-PCjJRJJa3Yl4AqL4WXDwUxt-A-vpSyVWlJ_EbNk2GdSwv4vGDLeVS4XONFr6Sl4lUXrgMQ4AMnyEIwr4ms4POXnJb20nF87HM",
    "token_type": "bearer",
    "expires_in": 86399,
    "refresh_token": "fc833f6e009c4ca6bcc5a5720fa7c546",
    "as:client_id": "OtherApp",
    "UserId": "13315",
    "InstituteId": "0",
    "FinancialYearId": "0",
    "UserType": "S",
    "StudentId": "59110",
    "StudDetail": "JSON String",
    ".issued": "Fri, 13 May 2022 03:35:03 GMT",
    ".expires": "Sat, 14 May 2022 03:35:03 GMT"
}

I have check the response in App Interceptor, it shows response body but when I check Response response is null.

I created retrofit object in postData method in MainActivity:

private void postData(String username, String password){

        LoginRequest request = new LoginRequest(username, password);

        Map<String, String> map = new HashMap<>();
        map.put("username",request.getUsername());
        map.put("password", request.getPassword());
        map.put("grant_type",request.getGrant_type());
        map.put("client_id",request.getClient_id());
        map.put("client_secret",request.getClient_secret());

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(base_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PostData pst = retrofit.create(PostData.class);

        Call<Respond> call = pst.createPost(map);

        call.enqueue(new Callback<Respond>() {
            @Override
            public void onResponse(Call<Respond> call, Response<Respond> response) {

                if (response.body() != null){

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, String.valueOf(response.code()),Toast.LENGTH_LONG).show();
                        }
                    });

                }

                if(response.isSuccessful()) {

//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(MainActivity.this, "in response", Toast.LENGTH_LONG).show();
//                        }
//                    });

                    Intent Homep = new Intent(getApplicationContext(), HomePagee.class)
                                        .putExtra("Student_Details",response.body().getStudDetail());

                    startActivity(Homep);
                }


            }

            @Override
            public void onFailure(Call<Respond> call, Throwable t) {

 //               runOnUiThread(new Runnable() {
 //                   @Override
 //                   public void run() {
 //                       Toast.makeText(MainActivity.this, "fail", Toast.LENGTH_LONG).show();
 //                   }
 //               });

            }
        });

    }

Api client is PostData:

package com.example.majorprojectapp;

import java.util.Map;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;

interface PostData {

    @FormUrlEncoded
    @POST("/NirmaLiveApi/token")
    Call<Respond> createPost(@FieldMap Map<String, String> fields);

}

I have used https://www.jsonschema2pojo.org/ to create Respond class and in all various classes the result is the same.

respond:

package com.example.majorprojectapp;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.io.Serializable;

public class Respond implements Serializable {

    @SerializedName("access_token")
    @Expose
    private String accessToken;
    @SerializedName("token_type")
    @Expose
    private String tokenType;
    @SerializedName("expires_in")
    @Expose
    private Integer expiresIn;
    @SerializedName("refresh_token")
    @Expose
    private String refreshToken;
    @SerializedName("as:client_id")
    @Expose
    private String asClientId;
    @SerializedName("UserId")
    @Expose
    private String userId;
    @SerializedName("InstituteId")
    @Expose
    private String instituteId;
    @SerializedName("FinancialYearId")
    @Expose
    private String financialYearId;
    @SerializedName("UserType")
    @Expose
    private String userType;
    @SerializedName("StudentId")
    @Expose
    private String studentId;
    @SerializedName("StudDetail")
    @Expose
    private String studDetail;
    @SerializedName(".issued")
    @Expose
    private String issued;
    @SerializedName(".expires")
    @Expose
    private String expires;

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

    public String getTokenType() {
        return tokenType;
    }

    public void setTokenType(String tokenType) {
        this.tokenType = tokenType;
    }

    public Integer getExpiresIn() {
        return expiresIn;
    }

    public void setExpiresIn(Integer expiresIn) {
        this.expiresIn = expiresIn;
    }

    public String getRefreshToken() {
        return refreshToken;
    }

    public void setRefreshToken(String refreshToken) {
        this.refreshToken = refreshToken;
    }

    public String getAsClientId() {
        return asClientId;
    }

    public void setAsClientId(String asClientId) {
        this.asClientId = asClientId;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getInstituteId() {
        return instituteId;
    }

    public void setInstituteId(String instituteId) {
        this.instituteId = instituteId;
    }

    public String getFinancialYearId() {
        return financialYearId;
    }

    public void setFinancialYearId(String financialYearId) {
        this.financialYearId = financialYearId;
    }

    public String getUserType() {
        return userType;
    }

    public void setUserType(String userType) {
        this.userType = userType;
    }

    public String getStudentId() {
        return studentId;
    }

    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }

    public String getStudDetail() {
        return studDetail;
    }

    public void setStudDetail(String studDetail) {
        this.studDetail = studDetail;
    }

    public String getIssued() {
        return issued;
    }

    public void setIssued(String issued) {
        this.issued = issued;
    }

    public String getExpires() {
        return expires;
    }

    public void setExpires(String expires) {
        this.expires = expires;
    }

}

The response.isSuccessful() is true and is going in new page but the body is null. I am fairly new on Android and retrofit and have created this much from several videos.

Leave a Comment