import java.security.MessageDigest; /** * * @description : 网易云信API * @auhtor : ChengJing * @created : 2018/10/24 下午2:23 * */ public class CheckSumBuilder { // 计算并获取CheckSum public static String getCheckSum(String appSecret, String nonce, String curTime) { return encode("sha1", appSecret + nonce + curTime); } // 计算并获取md5值 public static String getMD5(String requestBody) { return encode("md5", requestBody); } private static String encode(String algorithm, String value) { if (value == null) { return null; } try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); messageDigest.update(value.getBytes()); return getFormattedText(messageDigest.digest()); } catch (Exception e) { throw new RuntimeException(e); } } private static String getFormattedText(byte[] bytes) { int len = bytes.length; StringBuilder buf = new StringBuilder(len * 2); for (int j = 0; j < len; j++) { buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[bytes[j] & 0x0f]); } return buf.toString(); } private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; }
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xinluo.app.common.entity.netease.NeteaseCommunicationResponse;
import com.xinluo.app.common.entity.user.Patient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @author : ChengJing
* @description : 网易云通信工具类
* @date: Created in 下午2:27 2018/10/24
*/
@Component
public class NeteaseCommunicationUtil {
private Logger logger = LogManager.getLogger(this.getClass());
@Value("${netease.appKey}")
protected String appKey;
@Value("${netease.appSecret}")
protected String appSecret;
/**
* 创建网易云信用户
* @param : accid 用户环信id/token信息
* @return :
*/
public NeteaseCommunicationResponse createNeteaseCommunicationUser(String neteaseCommunicationAccountId) throws IOException {
logger.info("************************** 创建网易云信用户 **************************");
DefaultHttpClient httpClient = new DefaultHttpClient();
String url = "https://api.netease.im/nimserver/user/create.action";
HttpPost httpPost = new HttpPost(url);
String nonce = UUID.randomUUID().toString();
String curTime = String.valueOf((new Date()).getTime() / 1000L);
//参考 计算CheckSum的java代码
String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);
// 设置请求的header
httpPost.addHeader("AppKey", appKey);
httpPost.addHeader("Nonce", nonce);
httpPost.addHeader("CurTime", curTime);
httpPost.addHeader("CheckSum", checkSum);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// 设置请求的参数
List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("accid", neteaseCommunicationAccountId));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
// 执行请求
HttpResponse response = httpClient.execute(httpPost);
JSONObject existJsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
NeteaseCommunicationResponse neteaseCommunicationResponse = existJsonObject.toJavaObject(NeteaseCommunicationResponse.class);
return neteaseCommunicationResponse;
}
/**
* 更新网易云信用户token
* @param : accid 用户环信id/token信息
* @return :
*/
public NeteaseCommunicationResponse updateNeteaseCommunicationUserToken(String neteaseCommunicationAccountId) throws IOException {
logger.info("************************** 更新网易云信用户token **************************");
DefaultHttpClient httpClient = new DefaultHttpClient();
String url = "https://api.netease.im/nimserver/user/refreshToken.action";
HttpPost httpPost = new HttpPost(url);
String nonce = UUID.randomUUID().toString();
String curTime = String.valueOf((new Date()).getTime() / 1000L);
//参考 计算CheckSum的java代码
String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);
// 设置请求的header
httpPost.addHeader("AppKey", appKey);
httpPost.addHeader("Nonce", nonce);
httpPost.addHeader("CurTime", curTime);
httpPost.addHeader("CheckSum", checkSum);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// 设置请求的参数
List nvps = new ArrayList();
nvps.add(new BasicNameValuePair("accid", neteaseCommunicationAccountId));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
// 执行请求
HttpResponse response = httpClient.execute(httpPost);
JSONObject existJsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
NeteaseCommunicationResponse neteaseCommunicationResponse = existJsonObject.toJavaObject(NeteaseCommunicationResponse.class);
return neteaseCommunicationResponse;
}
}
/**
* 注册网易云通信用户
* @param :
* @return :
*/
private void createNeteaseCommunicationUser(Patient patient,String neteaseCommunicationAccountId) throws Exception{
//创建网易云信账号
try {
NeteaseCommunicationResponse neteaseCommunicationUser = neteaseCommunicationUtil.createNeteaseCommunicationUser(neteaseCommunicationAccountId);
if (StateConstant.SUCCESS.equals(neteaseCommunicationUser.getCode())){
patient.setNeteaseCommunicationAccid(neteaseCommunicationAccountId);
patient.setNeteaseCommunicationToken(neteaseCommunicationUser.getInfo().getToken());
logger.info(" ************** 网易云信注册账号成功 ************** ");
}
logger.info(" ************** 1. 网易云返回 ************** "+neteaseCommunicationUser);
if(CommonConstant.NETEASE_ACCOUNT_AREADY_EXIST_CODE.equals(neteaseCommunicationUser.getCode())
&& CommonConstant.NETEASE_ACCOUNT_AREADY_EXIST_DESC.equals(neteaseCommunicationUser.getDesc())){
NeteaseCommunicationResponse neteaseCommunicationResponse = neteaseCommunicationUtil.updateNeteaseCommunicationUserToken(neteaseCommunicationAccountId);
logger.info(" **************2. 网易云返回 ************** "+neteaseCommunicationResponse);
if(StateConstant.SUCCESS.equals(neteaseCommunicationResponse.getCode())){
patient.setNeteaseCommunicationAccid(neteaseCommunicationAccountId);
patient.setNeteaseCommunicationToken(neteaseCommunicationResponse.getInfo().getToken());
logger.error(" ************** 网易云通信账号已注册, 更新token并返回 ************** ");
}
}
} catch (IOException e){
logger.error(" ************** 网易云信注册账号失败 ************** "+e.getMessage(),e);
throw new Exception("网易云信注册账号/更新token失败");
}
}
接入网易云信过程,记录下