使用hutool工具类生成token

  • Post author:
  • Post category:其他


1、pom文件引入hutool依赖包

<dependencies>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.8.5</version>
    </dependency>
</dependencies>

2、创建获取token工具类

public class TestUtil {
    private static String token = null;
    
    public static String getToken(){
        JSONObject params = new JSONObject();
        params.put("username","username");
        params.put("password","password");

        String loginUrl = "系统登录地址";

        String str = HttpUtil.createPost(loginUrl).contentType("application/json")
                .body(params.toString()).execute().body();

        JSONObject jsonObject = JSONUtil.parseObj(str);

        Integer code = jsonObject.getInt("code");
        if (code == 200){
            JSONObject data = jsonObject.getJSONObject("data");
            token = "Bearer" + data.getStr("access_token");

            return token;
        }else {
            System.out.println(jsonObject.toString());
            return null;
        }
    }
}

3、调用获取token方法

public static void main(String[] args) {
    String token = TestUtil.getToken();
    System.out.println(token);
}



版权声明:本文为Y175123213原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。