You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java调用WordPress Rest API获取JWT Token报错:无法解析getString方法

问题解决:正确从JWT响应中提取Token

你遇到的问题是OkHttp的Response对象本身没有getString()方法,这个方法属于JSONObject类。你已经获取了响应字符串resStr,只需要把这个字符串转换成JSONObject,再从中提取Token即可。

核心修正代码

在responseCode == 200的判断块中替换原有错误逻辑:

if (responseCode == 200) {
    try {
        // 将响应字符串转为JSON对象
        JSONObject responseJson = new JSONObject(resStr);
        // 从JSON对象中提取token字段
        String token = responseJson.getString("token");
        
        Log.i("We're logged in!", "Token已获取");
        Log.i("Response Code", String.valueOf(responseCode));

        Intent i = new Intent(LoginActivity.this, DashboardActivity.class);
        startActivity(i);
    } catch (JSONException e) {
        e.printStackTrace();
        Log.e("解析错误", "JSON解析失败: " + e.getMessage());
    }
}

完整修正后的代码片段

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) {
        try {
            JSONObject responseJson = new JSONObject(resStr);
            String token = responseJson.getString("token");
            
            Log.i("We're logged in!", "Token获取成功");
            Log.i("Response Code", String.valueOf(responseCode));

            Intent i = new Intent(LoginActivity.this, DashboardActivity.class);
            startActivity(i);
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("错误", "JSON解析失败: " + e.getMessage());
        }
    } else {
        Log.e("登录失败", "响应码: " + responseCode);
    }
} catch (IOException e) {
    e.printStackTrace();
    Log.e("网络错误", "请求失败: " + e.getMessage());
} finally {
    // 关闭响应体,避免资源泄漏
    if (response != null) {
        response.close();
    }
}

关键说明

  1. 基于响应字符串解析JSON:必须使用你已经获取的resStr来创建JSONObject,而非直接操作OkHttp的Response对象。
  2. 异常捕获:JSON转换和字段提取可能抛出JSONException,必须捕获处理防止程序崩溃。
  3. 资源释放:使用完Response后调用close(),避免OkHttp资源泄漏。

内容的提问来源于stack exchange,提问作者Brittany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:06:45