0

I send a post request to a server via the help of Retrofit but i want to get a value from a token when the server sends a response back. This is how i send my post request and onSuccess i want to receive the token. My problem here is that i don't know to retrieve the token from the server response. Kindly help here.

public void loginUser(String userName, String userPassword, Boolean userRememberMe) {

    mAPIService.loginUser(userName, userPassword, userRememberMe).enqueue(new Callback<Login>() {
        @Override
        public void onResponse(Response<Login> response, Retrofit retrofit) {
            if(response.isSuccess()) {
                //save token here
                Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
                startActivity(intent);
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            Log.e(TAG, "Unable to Login");
        }
    });
}

This is the response i get from the server

{
 "total": 0,
 "data": {
"id": "348680c7-d46b-4adc-9be0-89a1d1a38566",
"username": "0242770336",
"name": "name",
"phoneNumber": "063546345",
"email": "number@gmail.com",
"dateOfBirth": null,
"image": null,
"gender": "",
"idTypeId": null,
"idType": null,
"idNumber": null,
"idExpiryDate": null,
"idVerified": false,
"cityId": null,
"city": null,
"residentialAddress": null,
"latitude": 0,
"longitude": 0,
"createdAt": "2017-08-14T17:45:16.24Z",
"role": {
  "id": 2,
  "name": "User",
  "privileges": [
    ""
  ]
},
"token": "jNK_DGszYOMEpPOFoRGjuyJ5KX9kaJQKCl3cujlHoXklCS8Ij6b-QBmhv0jVwVC54KcNXkzyM62xpswqcjo9Ajf-n-rWzSaIoiYNglaXhtPspziZ0PcTKzTMAvw8si3A7BlcD98M-IjIxYjxieVYAPWVtcvomWi"
},

"message": "Login Successfull",
"success": true
}

This is my Login Model

public class Login {

@SerializedName("userName")
@Expose
private String userName;
@SerializedName("password")
@Expose
private String password;
@SerializedName("rememberMe")
@Expose
private Boolean rememberMe;

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public Boolean getRememberMe() {
    return rememberMe;
}

public void setRememberMe(Boolean rememberMe) {
    this.rememberMe = rememberMe;
}

}

Lending Square
  • 201
  • 1
  • 5
  • 14

5 Answers5

3

There are two approaches to this.

method 1 :use JsonObject

mAPIService.loginUser(userName, userPassword, userRememberMe).enqueue(new Callback<JsonObject>() {
    @Override
public void onResponse(Response<JsonObject> response, Retrofit retrofit) {
       if(response.isSuccess()) {
         try {

           String token=response.body().get("data").get("token");
        } catch (JSONException e) {
              e.printStackTrace();
         }
Intent intent = new Intent(LoginActivity.this,ProfileActivity.class);
startActivity(intent);
    }
}
}

method 2: you can use http://pojo.sodhanalibrary.com/ to convert your response to POJO. now add it to your project and let's name it ResponseData.class and get token using getter method by doing to following changes

mAPIService.loginUser(userName, userPassword, userRememberMe).enqueue(new Callback<ResponseData>() {
    @Override
    public void onResponse(Response<ResponseData> response, Retrofit retrofit) {
        if(response.isSuccess()) {
            //save token here
String token =response.getData().getToken();

            Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onFailure(Throwable throwable) {
        Log.e(TAG, "Unable to Login");
    }
});
  • in the first option i would have an error if the callback is enqueued on the Login Model. What do you suggest i do in this case. – Lending Square Aug 17 '17 at 15:54
  • my request model is different from my response model. Check my updated question. – Lending Square Aug 17 '17 at 16:03
  • Callback takes Response Model as a parameter so cannot use login model there as your response is different than response. what thing you need to change is that your retrofit request should return call or Call and not call – Chandan Bhandari Aug 18 '17 at 06:09
  • an example of your retrofit request @POST(Common.Urls.RESET_PASSWORD_API) Call loginUser(@Body HashMap request); – Chandan Bhandari Aug 18 '17 at 06:14
  • Thank you for your answer i was able to retrieve the token. – Lending Square Aug 18 '17 at 12:09
  • how do i add the token as a header to every request i send to the server. I would save the token to sharedPreferences so i can have access to it anytime i need to use it in the retrofit header. – Lending Square Aug 18 '17 at 12:11
  • https://stackoverflow.com/questions/32963394/how-to-use-interceptor-to-add-headers-in-retrofit-2-0 – Chandan Bhandari Aug 20 '17 at 06:19
0

Convert the response string into JSONObject and then again get the JSONObject for data and in data you can find your token object.

JSONObject  object  = new JSONObject(response);
JSONObject dataObject = object.getJSONObject("data");
String token = dataObject.getString("token");
Log.i("TAG","token is "+token);
Nouman Ch
  • 4,023
  • 4
  • 29
  • 42
0

Try this.

Use optBoolean() method and optString() method

try {
        JSONObject jsonObject = new JSONObject(response);
        boolean success = jsonObject.optBoolean("success");
        if (success) {
            JSONObject data = jsonObject.getJSONObject("data");
            String token = data.optString("token");
        } else {
            Log.e("message", "failure");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
0

You can use Gson to convert you json to a java POJO class. However if you just want to get the token field you can use it like this:

public void onResponse(Response<Login> response, Retrofit retrofit) {
        if(response.isSuccess()) {
             try {
        JSONObject ob = new JSONObject(response.body());
        String token = ob.getJSONObject("data").getString("token");

    } catch (JSONException e) {
        e.printStackTrace();
    }
            Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
            startActivity(intent);
        }
    }
M.Waqas Pervez
  • 2,492
  • 2
  • 19
  • 33
0

for this you need to first understand that this response is in Json format you need to first create the Json object from the response you get from server . for better understanding https://www.androidhive.info/2012/01/android-json-parsing-tutorial/ http://www.json.org/ and code to get that response.

try{
       JSONObject jsonObject = new JSONObject(response);
        String token = jsonObject.getJSONObject("data").getString("token");
}
catch(JSONException e){
e.printstacktrace();
}
R7G
  • 1,000
  • 1
  • 10
  • 15