ApiGwUtils.java 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package com.dragonsoft.dcuc.approvegateway.util;
  2. import com.alibaba.fastjson.JSON;
  3. import com.dragonsoft.approve.common.ErrorCode;
  4. import com.dragonsoft.approve.model.TokenInfo;
  5. import com.dragonsoft.duceap.base.exception.ApplicationException;
  6. import com.google.gson.Gson;
  7. import com.google.gson.GsonBuilder;
  8. import org.apache.http.HttpException;
  9. import org.apache.http.HttpResponse;
  10. import org.apache.http.NameValuePair;
  11. import org.apache.http.client.ClientProtocolException;
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;
  13. import org.apache.http.client.methods.HttpPost;
  14. import org.apache.http.client.utils.URIBuilder;
  15. import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
  16. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  17. import org.apache.http.impl.client.CloseableHttpClient;
  18. import org.apache.http.impl.client.HttpClients;
  19. import org.apache.http.message.BasicNameValuePair;
  20. import org.apache.http.protocol.HTTP;
  21. import org.apache.http.util.EntityUtils;
  22. import org.slf4j.Logger;
  23. import org.slf4j.LoggerFactory;
  24. import javax.net.ssl.SSLContext;
  25. import javax.net.ssl.TrustManager;
  26. import javax.net.ssl.X509TrustManager;
  27. import java.io.IOException;
  28. import java.net.URISyntaxException;
  29. import java.security.KeyManagementException;
  30. import java.security.NoSuchAlgorithmException;
  31. import java.security.cert.CertificateException;
  32. import java.security.cert.X509Certificate;
  33. import java.util.ArrayList;
  34. import java.util.List;
  35. /**
  36. * 代码千万行,注释第一行,编码不规范,同事两行泪
  37. *
  38. * @author huang(jy)
  39. * @version 1.0
  40. * @date 2020/12/16 19:25
  41. */
  42. public class ApiGwUtils {
  43. private static final Logger logger = LoggerFactory.getLogger(ApiGwUtils.class);
  44. private final static String GRANT_TYPE = "client_credentials";
  45. private final static String SCOPE = "default";
  46. private static final String DATA_FORMAT = "yyyy-MM-dd HH:mm:ss";
  47. /**
  48. * 返回完整的值
  49. *
  50. * @param clientId
  51. * @param clientSecret
  52. * @return
  53. */
  54. public static TokenInfo getHuaweiTokenObj2(String clientId, String clientSecret, String requestUrl) {
  55. TokenInfo hwTokenInfo = new TokenInfo();
  56. try {
  57. hwTokenInfo = getToken(clientId, clientSecret, requestUrl);
  58. } catch (HttpException e) {
  59. e.printStackTrace();
  60. }
  61. return hwTokenInfo;
  62. }
  63. /**
  64. * 获取Token信息
  65. *
  66. * @param appKey 用户凭证中的 AppKey
  67. * @param secretKey 用户凭证中的 SecretKey
  68. * @return HwTokenInfo Token信息
  69. */
  70. public static TokenInfo getToken(String appKey, String secretKey, String requestUrl) throws HttpException {
  71. // 添加请求体内容
  72. List<NameValuePair> pairs = new ArrayList<NameValuePair>();
  73. pairs.add(new BasicNameValuePair("grant_type", GRANT_TYPE));
  74. pairs.add(new BasicNameValuePair("client_id", appKey));
  75. pairs.add(new BasicNameValuePair("client_secret", secretKey));
  76. pairs.add(new BasicNameValuePair("scope", SCOPE));
  77. String result = httpsForPostRequest(pairs, requestUrl);
  78. return toObject(result, TokenInfo.class);
  79. }
  80. /**
  81. * 获取token
  82. *
  83. * @return
  84. */
  85. public static TokenInfo getAccessToken(String requestUrl, String clientId, String clientSecret) {
  86. logger.info("【verifyIdCard】:apigwUrl:{},clientId:{},clientSecret:{}", requestUrl, clientId, clientSecret);
  87. TokenInfo tokenInfo = null;
  88. try {
  89. tokenInfo = ApiGwUtils.getHuaweiTokenObj2(clientId, clientSecret, requestUrl);
  90. logger.info("【getAccessToken】获取token接口返回的信息:{}", JSON.toJSONString(tokenInfo));
  91. } catch (Exception e) {
  92. logger.error("【getAccessToken】获取token接口失败", e);
  93. throw new ApplicationException(ErrorCode.HW_ACCESS_TOKEN_FAIL.getCode(), ErrorCode.HW_ACCESS_TOKEN_FAIL.getMsg());
  94. }
  95. return tokenInfo;
  96. }
  97. /**
  98. * 刷新AccessToken有效期
  99. *
  100. * @param appKey 用户凭证中的 AppKey
  101. * @param secretKey 用户凭证中的 SecretKey
  102. * @param refreshToken Token信息中用于刷新有效期的 refresh_token
  103. * @return HwTokenInfo Token信息
  104. */
  105. public static TokenInfo refreshToken(String appKey, String secretKey, String huaweiUrl, String refreshToken) throws HttpException {
  106. // 添加请求体内容
  107. List<NameValuePair> pairs = new ArrayList<NameValuePair>();
  108. pairs.add(new BasicNameValuePair("grant_type", "refresh_token"));
  109. pairs.add(new BasicNameValuePair("client_id", appKey));
  110. pairs.add(new BasicNameValuePair("client_secret", secretKey));
  111. pairs.add(new BasicNameValuePair("refresh_token", refreshToken));
  112. String result = httpsForPostRequest(pairs, huaweiUrl);
  113. return toObject(result, TokenInfo.class);
  114. }
  115. /**
  116. * https的POST请求
  117. *
  118. * @param data
  119. * @return
  120. * @throws HttpException
  121. */
  122. public static String httpsForPostRequest(List<NameValuePair> data, String requestUrl) throws HttpException {
  123. SSLContext sslContext;
  124. CloseableHttpClient client;
  125. String result = "";
  126. try {
  127. // 创建Http客户端,设置信任自签名证书
  128. sslContext = SSLContext.getInstance("TLSv1.2");
  129. sslContext.init(null, new TrustManager[]{TRUST_ALL}, null);
  130. SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
  131. new AllowAllHostnameVerifier());
  132. client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
  133. // 创建POST请求,添加URL
  134. URIBuilder uriBuilder = new URIBuilder(requestUrl);
  135. HttpPost httpPost = new HttpPost(uriBuilder.build());
  136. httpPost.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
  137. // 添加请求头
  138. httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
  139. // 发送请求
  140. HttpResponse response = client.execute(httpPost);
  141. // 解析响应内容
  142. if (response.getStatusLine().getStatusCode() == 200) {
  143. result = EntityUtils.toString((response).getEntity());
  144. } else {
  145. throw new HttpException(response.getStatusLine() + EntityUtils.toString((response).getEntity()));
  146. }
  147. } catch (NoSuchAlgorithmException e) {
  148. e.printStackTrace();
  149. } catch (KeyManagementException e) {
  150. e.printStackTrace();
  151. } catch (URISyntaxException e) {
  152. e.printStackTrace();
  153. } catch (ClientProtocolException e) {
  154. e.printStackTrace();
  155. } catch (IOException e) {
  156. e.printStackTrace();
  157. }
  158. return result;
  159. }
  160. private static X509TrustManager TRUST_ALL = new X509TrustManager() {
  161. public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  162. }
  163. public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  164. }
  165. public X509Certificate[] getAcceptedIssuers() {
  166. return new X509Certificate[0];
  167. }
  168. };
  169. public static <T> T toObject(String json, Class<T> valueType) {
  170. Gson gson = new GsonBuilder().setDateFormat(DATA_FORMAT).serializeNulls().create();
  171. return gson.fromJson(json, valueType);
  172. }
  173. public static void main(String[] args) {
  174. String a = "{\"access_token\":\"12\"}";
  175. getAccessToken("", "", "");
  176. System.out.println();
  177. }
  178. }