http的util类,通过http请求向飞书请求并获取user_access_token实现免登录

doPostJson方法:传入参数为,请求地址,请求体的json,请求头的map,返回为封装的jsonString

public static String doPostJson(String url, String json,Map headers) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
.setConnectionRequestTimeout(1000)
.setSocketTimeout(5000).build();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 创建请求头
if(headers != null){
for (String key : headers.keySet()) {
httpPost.addHeader(key,headers.get(key).toString());
}
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return resultString;
}

飞书相关获取token方法:

/**
* 获取飞书AppAccessToken
* @return
*/

public static String getAppAccessToken() {
Map headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
FeiShuAppAccessTokenVO appAccessTokenVO = null;
JSONObject relationFileReq = new JSONObject();
relationFileReq.put(FeiShuConstant.APP_ID, APPID);
relationFileReq.put(FeiShuConstant.APP_SECRET, APP_SECRET);
try {
String result = HttpClientUtil.doPostJson(GET_APP_ACCESS_TOKEN, relationFileReq.toJSONString(), headers);
appAccessTokenVO = JSONObject.parseObject(result, FeiShuAppAccessTokenVO.class);
log.info("飞书响应{}",appAccessTokenVO);
} catch (Exception e) {
log.error("获取飞书APPAccessToken失败!{}",e);
}
return appAccessTokenVO!=null?appAccessTokenVO.getApp_access_token():null;
}

先根据appkey和secret获取到apptoken,然后根据apptoken和前端传回来的code,获取userAccessToken,根据官方提供的返回值,自己封装成response对象,然后把json转为对象获取对应需要的用户信息。这里获取到用户的手机号,然后做一个用户校验。如果是本公司用户,那么直接返回手机号和验证码给前端,再次调用登录接口就实现免登录了
/**
* 获取飞书的UserAccessToken
* @param accessToken
* @param code
* @return
*/
public String getUserAccessToken(String accessToken,String code) {

Map headers = new HashMap<>();
JSONObject relationFileReq = new JSONObject();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", "Bearer " + accessToken);
relationFileReq.put("grant_type", "authorization_code");
relationFileReq.put("code", code);
FeiShuUserAccessTokenVO feiShuUserAccessTokenVO = null;
try {
String result = HttpClientUtil.doPostJson(GET_USER_ACCESS_TOKEN, relationFileReq.toJSONString(), headers);
feiShuUserAccessTokenVO = JSONObject.parseObject(result, FeiShuUserAccessTokenVO.class);
log.info("飞书响应{}", feiShuUserAccessTokenVO);
} catch (Exception e) {
log.error("获取飞书UserAccessToken失败!{}", e);
}
return feiShuUserAccessTokenVO != null ? feiShuUserAccessTokenVO.getData().getMobile().substring(3) : null;

}

你可能感兴趣的:(http,飞书,java)