获取更新Token工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.baiyz.test;  

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sensorsdata.utils.HttpDriver;
import com.sensorsdata.utils.MyETLRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.http.Consts;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicBoolean;

/**
* <p> * Description: 获取token工具类
* </p >
* <p>PackageName: com.baiyz.test</p > * <p>ClassName: TestTokenFetcher</p > * * @author <a href="mail to: byz0825@outlook.com" rel="nofollow">BaiYZ</a >
* @since 2022-09-16 10:04:53
*/@Slf4j
public class TestTokenFetcher {

/**
* 自旋锁标记
*/
private static final AtomicBoolean shuShuoTokenStatus = new AtomicBoolean();
/**
* token */ private static String token = "";
/**
* <b>刷新Token的一种方法</b>
* * @return token
* @throws IOException httpIO异常
* @throws ParseException 类型转化异常
* @throws MyETLRuntimeException 处理获取Token异常
*/
public static String refreshToken() throws IOException, ParseException {
if (shuShuoTokenStatus.compareAndSet(false, true)) {
log.info("开始刷新token" + Thread.currentThread().getName());
JSONObject reqBody = new JSONObject();
//存入reqBody中获取token所需的信息
//情请求路径
String url = "";
//org.apache.hc.client5.http.classic.methods
HttpPost httpPost = new HttpPost(url);
//设置请求体类型
StringEntity stringEntity = new StringEntity(reqBody.toJSONString(), Consts.UTF_8);
//设置请求头
httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
httpPost.setEntity(stringEntity);
//尝试并执行
try (CloseableHttpResponse response = HttpDriver.client.execute(httpPost)) {
final String content = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
JSONObject jsonObject = JSON.parseObject(content);
//解码响应中的token
token = (String) jsonObject.getJSONObject("result").get("token");
return token;
} finally {
shuShuoTokenStatus.set(false);
} } throw new RuntimeException("抛出自定义异常信息");
}}