2

the response from the server as below:

{
    success: true,
    token: "someRandomToken"
}

How can I retrieve token from the response?

I tried to follow the solution provided here but I can't add generic to the Call inside onResponse method

EDIT

Here is my method

public void loginUser(final Context context, String url, String username, String passowrd, loginJson loginjson) {

        final MediaType JSON
                = MediaType.parse("application/json; charset=utf-8");

        loginjson.setUsername(username);
        loginjson.setPassword(passowrd);

        Gson gson = new Gson();

        String jsonFromForm = gson.toJson(loginjson);

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON, jsonFromForm);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("content-type", "application/json; charset=utf-8")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("Failure!!");
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if(response.isSuccessful()) {
                    if (context != null) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {

                            @Override
                            public void run() {
                                if(response.body() != null){

                                }
                            }
                        });
                    }
//
                } else {
                    if (context != null) {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(context, context.getResources().getString(R.string.failed_to_login),
                                        Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                }
            }

        });


    }

After implementing @Piyush Patel answer: I change the Call and the Response to retrofit2.Call<tokenRetrieved> and retrofit2.Reponse<tokenRetrieved> respectively. but the Callback in my enqueue prompt an error asking me to implement its onResponse and onFailure methods

newbie question: Am I using retrofit1 methods?!!

Community
  • 1
  • 1
Behrouz Riahi
  • 1,751
  • 2
  • 21
  • 42
  • First of all you are using okhttp for requesting API you need to import compile 'com.squareup.retrofit2:retrofit:2.2.0' compile 'com.squareup.okhttp3:okhttp:3.6.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' dependency in your app.gradle to use retrofit – Piyush Patel May 11 '17 at 10:03
  • @PiyushPatel whopps!!, thanks a lot man appreciate it – Behrouz Riahi May 11 '17 at 10:12
  • Its My pleasure..! if you have any query regarding retrofit just ask here I will respond you. – Piyush Patel May 11 '17 at 10:18
  • @PiyushPatel okay, thanks again :) – Behrouz Riahi May 11 '17 at 10:43
  • to parse data on response success does job for you with OkHttpClient if(response.body() != null){ JsonResponse jsonResponse=gson.fromJson(response.body(), JsonResponse.class); } – Piyush Patel May 11 '17 at 11:13

3 Answers3

4

Here is a snippet that shows how you can implement it using GSON

public class JsonResponse {

    public String success;
    public String token;

    public JsonResponse(String success, String token) {
        this.success = success;
        this.token = token;
    }
}

Call<JsonResponse> call = api.checkLevel(1);
        call.enqueue(new Callback<JsonResponse>() {
            @Override
            public void onResponse(Call<JsonResponse> call, Response<JsonResponse> response) {
                if (response.isSuccessful()) {
                    JsonResponse jsonResponse=response.body();
                }
            }

            @Override
            public void onFailure(Call<JsonResponse> call, Throwable t) {
            }
        });
Jonas
  • 6,915
  • 8
  • 35
  • 53
Piyush Patel
  • 371
  • 1
  • 5
  • 13
1

Using

Volley u can do so

Try this code

public void onResponse(String response) {

                    try {
                        JSONObject object=new JSONObject(response);
                        if ((object.getBoolean("success"))==true){
                            String Token=object.getString("token");
                        }else{
                            // enter else condition
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();

                    // json Exception

                    }

                }
Mohit Singh
  • 1,402
  • 1
  • 10
  • 19
0

Create a JSONObject from your response string and to get the string with the key token use

JSONObject json = new JSONObject(response);
json.getString("token");
Denny
  • 1,766
  • 3
  • 17
  • 37