Java-从响应中检索令牌



我通过将用户的凭据发布到WordPress的Rest API来验证我的用户。因此,它在JSON响应中返回一个令牌(JWT(。我试图检索该令牌,但在尝试获取字符串的行中不断出现错误?我使用的线路:

字符串令牌=response.getString("令牌"(;

给我错误:

无法解析"响应"中的方法"getString">

这行应该是什么样子?我的数据以JSON格式返回。我被难住了,因为我已经在各种例子中看到了这种语法。我觉得我错过了一些显而易见的东西。感谢您的帮助!请原谅我的Java新手。

我的代码:

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);

}

第一个问题是响应对象没有方法getString,并且基于共享代码,该代码片段返回响应的json字符串

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

在这种情况下,您只需要将字符串读取为JsonObject,并以这种方式获取属性

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

最新更新