开发者社区 问答 正文

Token 服务工具方法类有哪几种


测试类仅仅给出一个 Demo 程序,实际线上使用时,请根据业务情况自行改造 HTTP 请求的代码。

  1. public class Tools {
  2.     /**
  3.      * 计算签名,参数分别是参数对以及密钥
  4.      *
  5.      * @param requestParams 参数对,即参与计算签名的参数
  6.      * @param secretKey     密钥
  7.      * @return 签名字符串
  8.      * @throws NoSuchAlgorithmException
  9.      * @throws InvalidKeyException
  10.      */
  11.     public static String doHttpSignature(Map<String, String> requestParams, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException {
  12.         List<String> paramList = new ArrayList<String>();
  13.         for (Map.Entry<String, String> entry : requestParams.entrySet()) {
  14.             paramList.add(entry.getKey() + "=" + entry.getValue());
  15.         }
  16.         Collections.sort(paramList);
  17.         StringBuffer sb = new StringBuffer();
  18.         for (int i = 0; i < paramList.size(); i++) {
  19.             if (i > 0) {
  20.                 sb.append('&');
  21.             }
  22.             sb.append(paramList.get(i));
  23.         }
  24.         return macSignature(sb.toString(), secretKey);
  25.     }
  26.     /**
  27.      * @param text      要签名的文本
  28.      * @param secretKey 阿里云MQ secretKey
  29.      * @return 加密后的字符串
  30.      * @throws InvalidKeyException
  31.      * @throws NoSuchAlgorithmException
  32.      */
  33.     public static String macSignature(String text, String secretKey) throws InvalidKeyException, NoSuchAlgorithmException {
  34.         Charset charset = Charset.forName("UTF-8");
  35.         String algorithm = "HmacSHA1";
  36.         Mac mac = Mac.getInstance(algorithm);
  37.         mac.init(new SecretKeySpec(secretKey.getBytes(charset), algorithm));
  38.         byte[] bytes = mac.doFinal(text.getBytes(charset));
  39.         return new String(Base64.encodeBase64(bytes), charset);
  40.     }
  41.     /**
  42.      * 创建HTTPS 客户端
  43.      *
  44.      * @return 单例模式的客户端
  45.      * @throws KeyStoreException
  46.      * @throws UnrecoverableKeyException
  47.      * @throws NoSuchAlgorithmException
  48.      * @throws KeyManagementException
  49.      */
  50.     private static HttpClient httpClient = null;
  51.     public static HttpClient getHttpsClient() throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
  52.         if (httpClient != null) {
  53.             return httpClient;
  54.         }
  55.         X509TrustManager xtm = new X509TrustManager() {
  56.             @Override
  57.             public void checkClientTrusted(X509Certificate[] arg0, String arg1)
  58.                     throws CertificateException {
  59.             }
  60.             @Override
  61.             public void checkServerTrusted(X509Certificate[] arg0, String arg1)
  62.                     throws CertificateException {
  63.             }
  64.             @Override
  65.             public X509Certificate[] getAcceptedIssuers() {
  66.                 return new X509Certificate[]{};
  67.             }
  68.         };
  69.         SSLContext context = SSLContext.getInstance("TLS");
  70.         context.init(null, new TrustManager[]{xtm}, null);
  71.         SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
  72.         Registry<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create()
  73.                 .register("http", PlainConnectionSocketFactory.INSTANCE)
  74.                 .register("https", scsf).build();
  75.         PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(sfr);
  76.         httpClient = HttpClientBuilder.create().setConnectionManager(pcm).build();
  77.         return httpClient;
  78.     }
  79.     /**
  80.      * 发起HTTPS Get请求,并得到返回的JSON响应
  81.      *
  82.      * @param url    接口URL
  83.      * @param params 参数对
  84.      * @return
  85.      * @throws IOException
  86.      * @throws KeyStoreException
  87.      * @throws UnrecoverableKeyException
  88.      * @throws NoSuchAlgorithmException
  89.      * @throws KeyManagementException
  90.      */
  91.     public static JSONObject httpsGet(String url, Map<String, String> params) throws IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {
  92.         HttpClient client = Tools.getHttpsClient();
  93.         JSONObject jsonResult = null;
  94.         //发送get请求
  95.         List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
  96.         for (Map.Entry<String, String> entry : params.entrySet()) {
  97.             urlParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  98.         }
  99.         String paramUrl = URLEncodedUtils.format(urlParameters, Charset.forName("UTF-8"));
  100.         HttpGet request = new HttpGet(url + "?" + paramUrl);
  101.         HttpResponse response = client.execute(request);
  102.         if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  103.             String strResult = EntityUtils.toString(response.getEntity());
  104.             jsonResult = JSON.parseObject(strResult);
  105.         }
  106.         return jsonResult;
  107.     }
  108.   /**
  109.      * 工具方法,发送一个HTTP POST请求,并尝试将响应转换为JSON
  110.      *
  111.      * @param url    请求的方法名URL
  112.      * @param params 参数表
  113.      * @return 如果请求成功则返回JSON,否则抛异常或者返回空
  114.      * @throws IOException
  115.      */
  116.     public static JSONObject httpsPost(String url, Map<String, String> params) throws IOException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
  117.         JSONObject jsonResult = null;
  118.         HttpClient client = getHttpsClient();
  119.         //发送get请求
  120.         HttpPost request = new HttpPost(url);
  121.         List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
  122.         for (Map.Entry<String, String> entry : params.entrySet()) {
  123.             urlParameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  124.         }
  125.         HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
  126.         request.setEntity(postParams);
  127.         HttpResponse response = client.execute(request);
  128.         if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  129.             String strResult = EntityUtils.toString(response.getEntity());
  130.             jsonResult = JSON.parseObject(strResult);
  131.         }
  132.         return jsonResult;
  133.     }
  134. }

展开
收起
猫饭先生 2017-10-27 10:49:20 1704 分享 版权
0 条回答
写回答
取消 提交回答