全部产品
存储与CDN 数据库 安全 应用服务 数加·人工智能 数加·大数据基础服务 互联网中间件 视频服务 阿里云办公 培训与认证 物联网
消息队列 MQ

工具方法类

更新时间:2017-08-25 14:15:39   分享:   

本文给出各个接口所需的工具方法类,包含如何计算签名,如何发起 HTTPS 请求等接口。

使用该测试类需要添加 HTTP 客户端的依赖,参考如下:

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5.2</version>
  5. </dependency>

测试类仅仅给出一个 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. }
本文导读目录
本文导读目录
以上内容是否对您有帮助?