You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
3.0 KiB

5 months ago
  1. package com.lh.until;
  2. import com.fasterxml.jackson.databind.JsonNode;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.lh.bean.dto.TokenDTO;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.entity.ContentType;
  9. import org.apache.http.entity.StringEntity;
  10. import org.apache.http.impl.client.CloseableHttpClient;
  11. import org.apache.http.impl.client.HttpClients;
  12. import org.apache.http.util.EntityUtils;
  13. import org.springframework.data.redis.core.StringRedisTemplate;
  14. import org.springframework.stereotype.Component;
  15. import javax.annotation.Resource;
  16. import java.io.IOException;
  17. import java.nio.charset.StandardCharsets;
  18. @Slf4j
  19. @Component
  20. public class Utils {
  21. @Resource
  22. private StringRedisTemplate stringRedisTemplate;
  23. // 获取token中的信息
  24. public TokenDTO analysisToken(String token) throws IOException {
  25. // 编码Token
  26. String url = "http://39.101.133.168:8828/hljw/api/v2/member/info";
  27. // 创建HttpClient实例
  28. try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
  29. // 创建POST请求
  30. HttpPost postRequest = new HttpPost(url);
  31. postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
  32. System.out.println(token);
  33. // 设置请求体参数
  34. StringEntity entity = new StringEntity(token, ContentType.APPLICATION_FORM_URLENCODED);
  35. postRequest.setEntity(entity);
  36. // 发送请求并获取响应
  37. try (CloseableHttpResponse response = httpClient.execute(postRequest)) {
  38. int responseCode = response.getStatusLine().getStatusCode(); // 获取状态码
  39. // 检查响应状态
  40. if (responseCode == 200) {
  41. // 读取响应体
  42. String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
  43. // 使用Jackson解析JSON响应体
  44. ObjectMapper objectMapper = new ObjectMapper();
  45. JsonNode jsonResponse = objectMapper.readTree(responseBody);
  46. JsonNode dataNode = jsonResponse.get("data");
  47. TokenDTO tokenDTO = new TokenDTO();
  48. tokenDTO.setJwcode(dataNode.get("jwcode").asInt());
  49. tokenDTO.setUsername(dataNode.get("username").asText());
  50. return tokenDTO;
  51. }
  52. else {
  53. throw new RuntimeException("Failed : HTTP error code : " + responseCode);
  54. }
  55. }
  56. }
  57. }
  58. // 获取token中的jwcode
  59. public Integer getJwcode(String token) throws IOException {
  60. TokenDTO dto = analysisToken(token);
  61. return dto.getJwcode();
  62. }
  63. public String getUsername(String token) throws IOException {
  64. TokenDTO dto = analysisToken(token);
  65. return dto.getUsername();
  66. }
  67. }