Java 使用HTTP请求直接获取oauth2.0的token,code

文章描述了如何使用Hutool库在Java中实现OAuth授权的三个步骤,包括发送POST请求获取code,以及利用Hutool处理body获取token的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 直接上代码

url写完整的:

"http://localhost:8083/oauth/" + "authorize"
+ "?client_id=" + clientId
+ "&response_type=" + "code"
+ "&scope=" + scope
+ "&redirect_uri=" + webServerRedirectUri;

这里需要发送三次http请求,有的应该两次就行,两次的我没写明白,用的时HuTool的工具

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

 private String getcode(String url, String username, String password) {
        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("username",username);
        stringStringHashMap.put("password",password);

        HttpRequest post = HttpRequest.post(url);
        HttpResponse execute = post.execute();
        String location1 = execute.header("Location");

        HttpResponse execute2 = HttpRequest.post(location1)
                .form(stringStringHashMap).execute();

        HttpRequest post3 = HttpRequest.post(url);
        HttpResponse execute3 = post3.execute();
        String location3 = execute3.header("Location");
        String code = location3.substring(location3.indexOf("=") + 1, location3.length());

        System.out.println(code);

        return code;
    }

下面时生成token的

hutool的body不用解析,直接就能用

 private String getToken(String urlToken) {
        HttpResponse execute = HttpRequest.post(urlToken)
                .execute();
        String body = execute.body();

        return body;
    }

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值