Home > Back-end >  Java - Retrieve token from response?
Java - Retrieve token from response?

Time:07-30

I'm authenticating my user by posting my user's credentials to WordPress's Rest API. As a result, it returns a token (JWT) in the JSON response. I'm trying to retrieve that token, but I keep getting an error in the line in which I try and grab the string? The line I'm using:

String token = response.getString("token");

Gives me the error:

Cannot resolve method 'getString' in 'Response'

What should this line look like instead? My data is returned in JSON format. I'm stumped, as I've seen that syntax in various examples. I feel like I'm missing something obvious. Help is appreciated! Pardon my Java newbness.

My code:

   JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("username", "admin");
                jsonObject.put("password", "password$232");

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

            OkHttpClient client = new OkHttpClient();
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            
            RequestBody body = RequestBody.create(JSON, jsonObject.toString());
            Request request = new Request.Builder()
                    .url("http://myurl.com/wp-json/jwt-auth/v1/token")
                    .post(body)
                    .build();

            Response response = null;
            try {
                response = client.newCall(request).execute();
                String resStr = response.body().string();
              
                int responseCode = response.code();
             

                if (responseCode == 200) {

                    System.out.println(response);

                    String token = response.getString("token");

                    Log.i("We're logged in!", String.valueOf(responseCode));

                    Intent i = new Intent(LoginActivity.this, DashboardActivity.class);
                    startActivity(i);


            }

CodePudding user response:

The first problem is that the response object doesn't have an method getString and based on the shared code this code fragment return the json string of the response

String resStr = response.body().string();

in this case you just need to read the string as an JsonObject and get the properties this way

 JSONObject respJson = new JSONObject(resStr);
 String token = respJson.getString("token");
  • Related