Test.java 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. package net.yyc.common.ding.entity;
  2. import io.micrometer.core.instrument.util.StringUtils;
  3. import org.apache.commons.io.IOUtils;
  4. import org.apache.http.NameValuePair;
  5. import org.apache.http.client.entity.UrlEncodedFormEntity;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.entity.StringEntity;
  9. import org.apache.http.impl.client.HttpClients;
  10. import org.jasypt.contrib.org.apache.commons.codec_1_3.binary.Base64;
  11. import javax.crypto.Mac;
  12. import javax.crypto.spec.SecretKeySpec;
  13. import java.io.*;
  14. import java.security.MessageDigest;
  15. import java.security.NoSuchAlgorithmException;
  16. import java.util.HashMap;
  17. import java.util.List;
  18. import java.util.Map;
  19. import java.util.TreeMap;
  20. public class Test {
  21. public static void main(String[] args) throws Exception {
  22. /**
  23. * 参数列表
  24. */
  25. String bodyStr = "{\n" +
  26. " \"freelances\": [\n" +
  27. " {\n" +
  28. " \"mobile\": \"15000998877\",\n" +
  29. " \"name\": \"张三\",\n" +
  30. " \"idType\": \"1\",\n" +
  31. " \"idCard\": \"350198765623418765\"\n" +
  32. " }\n" +
  33. " ]\n" +
  34. "}";
  35. String serviceSign = serviceSign("/oapi/v1/employ/freelances/check",
  36. "POST", new HashMap<>(), bodyStr.getBytes());
  37. System.out.println("serviceSign=========" + serviceSign);
  38. // 创建一个post对象
  39. String url = "https://test-f.renlijia.com/oapi/v1/employ/freelances/check";
  40. HttpPost post = new HttpPost(url);
  41. StringEntity s = new StringEntity(bodyStr, "UTF-8"); // 中文乱码在此解决
  42. s.setContentType("application/json");
  43. post.setEntity(s);
  44. post.setHeader("app-id","888999");
  45. post.setHeader("signature",serviceSign);
  46. // 执行post请求
  47. CloseableHttpResponse response = HttpClients.createDefault().execute(post);
  48. // String json = HttpClientUtils.doPost("https://test-f.renlijia.com", params);
  49. String result = fromStream(response.getEntity().getContent(), "UTF-8");
  50. System.out.println("result-----" + result);
  51. System.out.println("response=========" + response.getStatusLine().getStatusCode());
  52. System.out.println("response=========" + response.getEntity().getContent().toString());
  53. }
  54. private static String fromStream(InputStream is, String charset) throws IOException {
  55. BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  56. StringBuffer buffer = new StringBuffer();
  57. String line = "";
  58. while ((line = in.readLine()) != null) {
  59. buffer.append(line);
  60. }
  61. return new String(buffer.toString().getBytes("UTF-8"), charset);
  62. }
  63. /**
  64. * 签名算法HmacSha256
  65. */
  66. public static final String HMAC_SHA256 = "HmacSHA256";
  67. /**
  68. * 编码
  69. */
  70. public static final String ENCODING = "UTF-8";
  71. /**
  72. * 换⾏符
  73. */
  74. private static char LF = '\n';
  75. private static final String HTTP_METHOD_POST = "post";
  76. private static final String HTTP_METHOD_PUT = "put";
  77. /**
  78. * 26 * 获取请求签名
  79. * 27 *
  80. * 28 * @param uri 原始HTTP请求PATH(例:/oapi/v1/employ/free
  81. * lances/check)
  82. * 29 * @param httpMethod 原始HTTP请求⽅法(例:POST)5
  83. * 30 * @param paramsMap 原始HTTP请求所有Query+Form参数(POST请求:Ma
  84. * ps.newHashMap())
  85. * 31 * @param body 原始HTTP请求Body体(仅当请求为POST/PUT且⾮表
  86. * 单请求才需要设置此属性,表单形式的需要将参数放到paramsMap中)
  87. * 32 * @param appId ⽤户id
  88. * 33 * @return 签名结果
  89. * 34 * @throws Exception
  90. * 35
  91. */
  92. public static String serviceSign(String uri, String httpMethod, Map<String, Object> paramsMap, byte[] body) throws Exception {
  93. String bodyMd5 = buildBodyMd5(httpMethod, body);
  94. String resourceToSign = buildResource(uri, paramsMap);
  95. String stringToSign = buildStringToSign(resourceToSign,
  96. httpMethod, bodyMd5);
  97. Mac hmacSha256 = Mac.getInstance(HMAC_SHA256);
  98. String appSecret = "5T8134269D467IGa0ZC7s907666r2C43";
  99. byte[] keyBytes = appSecret.getBytes(ENCODING);
  100. hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.
  101. length, HMAC_SHA256));
  102. return new String(Base64.encodeBase64(hmacSha256.doFinal
  103. (stringToSign.getBytes(ENCODING))), ENCODING);
  104. }
  105. public static String buildBodyMd5(String httpMethod, byte[] body) throws IOException {
  106. if (body == null) {
  107. return null;
  108. }
  109. if (!httpMethod.equalsIgnoreCase(HTTP_METHOD_POST) && !httpMethod.equalsIgnoreCase(HTTP_METHOD_PUT)){
  110. return null;
  111. }
  112. InputStream inputStream = new ByteArrayInputStream(body);
  113. byte[] bodyBytes = IOUtils.toByteArray(inputStream);
  114. if (bodyBytes != null && bodyBytes.length > 0) {
  115. return base64AndMD5(bodyBytes).trim();
  116. }
  117. return null;
  118. }
  119. public static String base64AndMD5(byte[] bytes) {
  120. try {
  121. final MessageDigest md = MessageDigest.getInstance(
  122. "MD5");
  123. md.reset();
  124. md.update(bytes);
  125. final Base64 base64 = new Base64();
  126. return new String(base64.encode(md.digest()));
  127. } catch (final NoSuchAlgorithmException e) {
  128. throw new IllegalArgumentException("unknown algorith m MD5");
  129. }
  130. }
  131. public static String buildResource(String uri, Map<String, Object> paramsMap) {
  132. StringBuilder builder = new StringBuilder();
  133. builder.append(uri);
  134. TreeMap<String, Object> sortMap = new TreeMap<>();
  135. sortMap.putAll(paramsMap);
  136. if (sortMap.size() > 0) {
  137. builder.append('?');
  138. builder.append(buildMapToSign(sortMap));
  139. }
  140. return builder.toString();
  141. }
  142. public static String buildStringToSign(String resourceToSign, String method, String bodyMd5) {
  143. StringBuilder sb = new StringBuilder();
  144. sb.append(method).append(LF);
  145. if (StringUtils.isNotBlank(bodyMd5)) {
  146. sb.append(bodyMd5);
  147. }
  148. sb.append(LF);
  149. sb.append(resourceToSign);
  150. return sb.toString();
  151. }
  152. /**
  153. * 将Map转换为用&及=拼接的字符串
  154. */
  155. public static String buildMapToSign(Map<String, Object> paramMap) {
  156. StringBuilder builder = new StringBuilder();
  157. for (Map.Entry<String, Object> e : paramMap.entrySet()) {
  158. if (builder.length() > 0) {
  159. builder.append('&');
  160. }
  161. String key = e.getKey();
  162. Object value = e.getValue();
  163. if (value != null) {
  164. if (value instanceof List) {
  165. List list = (List) value;
  166. if (list.size() == 0) {
  167. builder.append(key);
  168. } else {
  169. builder.append(key).append("=").append(String.valueOf(list.get(0)));
  170. }
  171. } else if (value instanceof Object[]) {
  172. Object[] objs = (Object[]) value;
  173. if (objs.length == 0) {
  174. builder.append(key);
  175. } else {
  176. builder.append(key).append("=").append(String.valueOf(objs[0]));
  177. }
  178. } else {
  179. builder.append(key).append("=").append(String.valueOf(value));
  180. }
  181. }
  182. }
  183. return builder.toString();
  184. }
  185. public void check() throws IOException {
  186. String resourceToSign = "/oapi/v1/employ/freelances/check";
  187. String body ="{\"freelances\":[{\"mobile\":\"15000998877\",\"name\":\"张三\",\"idType\":\"1\",\n" +
  188. "\"idCard\":\"350198765623418765\"}]}";
  189. String bodyMd5 = buildBodyMd5(HTTP_METHOD_POST, body.getBytes());
  190. String stringToSign = buildStringToSign(resourceToSign, HTTP_METHOD_POST, bodyMd5);
  191. }
  192. }