package com.dragonsoft.dcuc.approvegateway.util; import com.alibaba.fastjson.JSON; import com.dragonsoft.approve.common.ErrorCode; import com.dragonsoft.approve.model.TokenInfo; import com.dragonsoft.duceap.base.exception.ApplicationException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ssl.AllowAllHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.net.URISyntaxException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; /** * 代码千万行,注释第一行,编码不规范,同事两行泪 * * @author huang(jy) * @version 1.0 * @date 2020/12/16 19:25 */ public class ApiGwUtils { private static final Logger logger = LoggerFactory.getLogger(ApiGwUtils.class); private final static String GRANT_TYPE = "client_credentials"; private final static String SCOPE = "default"; private static final String DATA_FORMAT = "yyyy-MM-dd HH:mm:ss"; /** * 返回完整的值 * * @param clientId * @param clientSecret * @return */ public static TokenInfo getHuaweiTokenObj2(String clientId, String clientSecret, String requestUrl) { TokenInfo hwTokenInfo = new TokenInfo(); try { hwTokenInfo = getToken(clientId, clientSecret, requestUrl); } catch (HttpException e) { e.printStackTrace(); } return hwTokenInfo; } /** * 获取Token信息 * * @param appKey 用户凭证中的 AppKey * @param secretKey 用户凭证中的 SecretKey * @return HwTokenInfo Token信息 */ public static TokenInfo getToken(String appKey, String secretKey, String requestUrl) throws HttpException { // 添加请求体内容 List pairs = new ArrayList(); pairs.add(new BasicNameValuePair("grant_type", GRANT_TYPE)); pairs.add(new BasicNameValuePair("client_id", appKey)); pairs.add(new BasicNameValuePair("client_secret", secretKey)); pairs.add(new BasicNameValuePair("scope", SCOPE)); String result = httpsForPostRequest(pairs, requestUrl); return toObject(result, TokenInfo.class); } /** * 获取token * * @return */ public static TokenInfo getAccessToken(String requestUrl, String clientId, String clientSecret) { logger.info("【verifyIdCard】:apigwUrl:{},clientId:{},clientSecret:{}", requestUrl, clientId, clientSecret); TokenInfo tokenInfo = null; try { tokenInfo = ApiGwUtils.getHuaweiTokenObj2(clientId, clientSecret, requestUrl); logger.info("【getAccessToken】获取token接口返回的信息:{}", JSON.toJSONString(tokenInfo)); } catch (Exception e) { logger.error("【getAccessToken】获取token接口失败", e); throw new ApplicationException(ErrorCode.HW_ACCESS_TOKEN_FAIL.getCode(), ErrorCode.HW_ACCESS_TOKEN_FAIL.getMsg()); } return tokenInfo; } /** * 刷新AccessToken有效期 * * @param appKey 用户凭证中的 AppKey * @param secretKey 用户凭证中的 SecretKey * @param refreshToken Token信息中用于刷新有效期的 refresh_token * @return HwTokenInfo Token信息 */ public static TokenInfo refreshToken(String appKey, String secretKey, String huaweiUrl, String refreshToken) throws HttpException { // 添加请求体内容 List pairs = new ArrayList(); pairs.add(new BasicNameValuePair("grant_type", "refresh_token")); pairs.add(new BasicNameValuePair("client_id", appKey)); pairs.add(new BasicNameValuePair("client_secret", secretKey)); pairs.add(new BasicNameValuePair("refresh_token", refreshToken)); String result = httpsForPostRequest(pairs, huaweiUrl); return toObject(result, TokenInfo.class); } /** * https的POST请求 * * @param data * @return * @throws HttpException */ public static String httpsForPostRequest(List data, String requestUrl) throws HttpException { SSLContext sslContext; CloseableHttpClient client; String result = ""; try { // 创建Http客户端,设置信任自签名证书 sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, new TrustManager[]{TRUST_ALL}, null); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build(); // 创建POST请求,添加URL URIBuilder uriBuilder = new URIBuilder(requestUrl); HttpPost httpPost = new HttpPost(uriBuilder.build()); httpPost.setEntity(new UrlEncodedFormEntity(data, "UTF-8")); // 添加请求头 httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); // 发送请求 HttpResponse response = client.execute(httpPost); // 解析响应内容 if (response.getStatusLine().getStatusCode() == 200) { result = EntityUtils.toString((response).getEntity()); } else { throw new HttpException(response.getStatusLine() + EntityUtils.toString((response).getEntity())); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } private static X509TrustManager TRUST_ALL = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; public static T toObject(String json, Class valueType) { Gson gson = new GsonBuilder().setDateFormat(DATA_FORMAT).serializeNulls().create(); return gson.fromJson(json, valueType); } public static void main(String[] args) { String a = "{\"access_token\":\"12\"}"; getAccessToken("", "", ""); System.out.println(); } }