PageRenderTime 42ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/netease/im/IMRequest.java

https://gitlab.com/zhyleng/activemq
Java | 178 lines | 134 code | 25 blank | 19 comment | 16 complexity | 6832e4d9c89c6a470220b34a0254c7f9 MD5 | raw file
  1. package com.netease.im;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.OutputStream;
  7. import java.io.UnsupportedEncodingException;
  8. import java.net.HttpURLConnection;
  9. import java.net.MalformedURLException;
  10. import java.net.URL;
  11. import java.security.MessageDigest;
  12. import java.security.NoSuchAlgorithmException;
  13. import java.util.UUID;
  14. import com.alibaba.fastjson.JSON;
  15. import com.alibaba.fastjson.JSONObject;
  16. public class IMRequest {
  17. private static final int HTTP_TIMEOUT = 30*1000;
  18. private static final String HTTP_METHOD_POST = "POST";
  19. private static final String HTTP_CHARSET = "UTF-8";
  20. private static final String HTTP_CONTENT_TYPE = "application/x-www-form-urlencoded;charset=utf-8";
  21. private static final String IM_ACCOUNT_CREATE = "https://api.netease.im/nimserver/user/create.action";
  22. private static final String APPKEY_KEY = "AppKey";
  23. private static final String NONCE_KEY = "Nonce";
  24. private static final String CURTIME_KEY = "CurTime";
  25. private static final String CHECKSUM_KEY = "CheckSum";
  26. private static final String CONTENT_TYPE_KEY = "Content-Type";
  27. private static final String APPKEY_VALUE = "6078ba08d1ebcc372d1ada46298bc13d";
  28. private static final String APPSECRET_VALUE = "ef1ac6d455fa";
  29. public static void main(String[] args) {
  30. System.out.println(JSON.toJSONString(createAccount(MD5.md5("12312312311", 32), "桔子zji", null, null)));
  31. }
  32. /**
  33. * 创建账号
  34. */
  35. public static IMResponse createAccount(String accid, String nickname, String icon, String token) {
  36. URL createAccountUrl = null;
  37. IMResponse resp = null;
  38. try {
  39. createAccountUrl = new URL(IM_ACCOUNT_CREATE);
  40. HttpURLConnection conn = (HttpURLConnection) createAccountUrl.openConnection();
  41. /** 设置参数 */
  42. conn.setConnectTimeout(HTTP_TIMEOUT);
  43. conn.setRequestMethod(HTTP_METHOD_POST);
  44. conn.setDoOutput(true);
  45. conn.setUseCaches(false);
  46. /** 请求实体 */
  47. StringBuffer entity = new StringBuffer("");
  48. entity.append("accid=" + accid + "&");
  49. entity.append("name=" + nickname + "&");
  50. if(icon != null) {
  51. entity.append("icon=" + icon + "&");
  52. }
  53. if(token != null) {
  54. entity.append("token=" + token + "&");
  55. }
  56. entity = entity.deleteCharAt(entity.length()-1);
  57. System.out.println("entity: " + entity);
  58. /** 设置请求头 */
  59. String nonce = UUID.randomUUID().toString();
  60. long curSeconds = System.currentTimeMillis()/1000;
  61. String checkSum = sha1(APPSECRET_VALUE + nonce + curSeconds);
  62. conn.addRequestProperty(APPKEY_KEY, APPKEY_VALUE);
  63. conn.addRequestProperty(NONCE_KEY, nonce);
  64. conn.addRequestProperty(CURTIME_KEY, String.valueOf(curSeconds));
  65. conn.addRequestProperty(CHECKSUM_KEY, checkSum);
  66. conn.addRequestProperty(CONTENT_TYPE_KEY, HTTP_CONTENT_TYPE);
  67. /** 连接 */
  68. conn.connect();
  69. /** POST实体 */
  70. OutputStream os = conn.getOutputStream();
  71. os.write(entity.toString().getBytes(HTTP_CHARSET));
  72. os.flush();
  73. os.close();
  74. String response = getText(conn);
  75. JSONObject obj = JSON.parseObject(response);
  76. if(obj.getIntValue("code") == 200) {
  77. resp = JSON.parseObject(obj.getString("info"), IMResponse.class);
  78. }
  79. System.out.println("response: " + response);
  80. } catch (MalformedURLException e) {
  81. e.printStackTrace();
  82. } catch (IOException e) {
  83. e.printStackTrace();
  84. }
  85. return resp;
  86. }
  87. /**
  88. * 对字符串进行 SHA1 加密
  89. * @param str
  90. * 待加密字符串
  91. * @return 加密后字符串
  92. */
  93. public static String sha1(String str) {
  94. char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  95. 'a', 'b', 'c', 'd', 'e', 'f' };
  96. MessageDigest sha1 = null;
  97. try {
  98. sha1 = MessageDigest.getInstance("SHA-1");
  99. sha1.update(str.getBytes("UTF-8"));
  100. } catch (NoSuchAlgorithmException e) {
  101. e.printStackTrace();
  102. throw new RuntimeException(e.getMessage());
  103. } catch (UnsupportedEncodingException e) {
  104. e.printStackTrace();
  105. throw new RuntimeException(e.getMessage());
  106. }
  107. byte[] encodedValue = sha1.digest();
  108. int j = encodedValue.length;
  109. char finalValue[] = new char[j * 2];
  110. int k = 0;
  111. for (int i = 0; i < j; i++) {
  112. byte encoded = encodedValue[i];
  113. finalValue[k++] = hexDigits[encoded >> 4 & 0xf];
  114. finalValue[k++] = hexDigits[encoded & 0xf];
  115. }
  116. return new String(finalValue);
  117. }
  118. /**
  119. * 获得连接请求的返回数据
  120. * @param conn
  121. * @return 字符串
  122. */
  123. private static String getText(HttpURLConnection conn) throws IOException {
  124. StringBuilder text = new StringBuilder();
  125. InputStream is = null;
  126. InputStreamReader sr = null;
  127. BufferedReader br = null;
  128. int code = conn.getResponseCode();
  129. is = code >= 400 ? conn.getErrorStream() : conn.getInputStream();
  130. sr = new InputStreamReader(is, "UTF-8");
  131. br = new BufferedReader(sr);
  132. char[] chars = new char[4096];
  133. int length = 0;
  134. while ((length = br.read(chars)) != -1) {
  135. text.append(chars, 0, length);
  136. }
  137. if (br != null) {
  138. br.close();
  139. br = null;
  140. }
  141. if (sr != null) {
  142. sr.close();
  143. sr = null;
  144. }
  145. if (is != null) {
  146. is.close();
  147. is = null;
  148. }
  149. if (code >= 400)
  150. throw new IOException(text.toString());
  151. return text.toString();
  152. }
  153. }