网易云通信 java 登录_Java接入网易云信工具类
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失败");
}
}
接入网易云信过程,记录下
网易云通信 java 登录_Java接入网易云信工具类相关推荐
- uuid java 重复_Java中使用UUID工具类生成唯一标志防止重复
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.secur ...
- 整装再出发! 网易云通信与视频2年接入40万开发者
2017年10月,网易云通信与视频正式迎来迎来两周年庆.在,两周年之际,网易云在产品端已实现通信与视频业务的战略升级,通过多元化和场景化的通信与视频的产品布局和完善的服务体系,为行业用户带来丰富的场景 ...
- 网易云信IM C#.Net请求、操作网易云通信ID
没啥技术含量就不写其他的了 直接上代码 using System; using System.Collections.Generic; using System.Configuration; usi ...
- 基于Selenium实现网易云音乐的登录
基于Selenium实现网易云音乐的登录 前言 一.准备工作 1.环境配置 2.确定页面的操作步骤 ①进入官网 ②点击登录 ③选择登录方式进行登录 二.代码实现 1.公共方法的封装 2.登录操作 总结 ...
- 小程序集成网易云通信群聊功能Demo发布
前端代码是可以直接使用的,获取后端代码加微信13439975582 功能实现说明: 1.小程序生命周期完美整合 2.消息小红点,群聊小红点代码实现都实现了 3.历史信息回放 4.小程序帐号集成 代码都 ...
- 网易云通信与视频业务升级 万维计划普及场景化云服务
5月24日,网易云通信与视频业务正式升级,将整合网易云信与网易视频云的技术和服务优势,并秉持"E=mc²"的全新价值观,为用户提供多场景.高稳定性.高可用的通信与视频云服务.同时, ...
- TOP100summit2017:网易云通信与视频CTO赵加雨:外力推动下系统架构的4个变化趋势...
壹佰案例:很荣幸邀请到您成为第六届壹佰案例峰会架构专场的联席主席,您曾深度参与Cisco Jabber,Webex Meeting, Cisco Spark等多项分布式实时通信类产品的架构与研发,您觉 ...
- TOP100summit2017:网易云通信与视频CTO赵加雨:外力推动下系统架构的4个变化趋势
壹佰案例:很荣幸邀请到您成为第六届壹佰案例峰会架构专场的联席主席,您曾深度参与Cisco Jabber,Webex Meeting, Cisco Spark等多项分布式实时通信类产品的架构与研发,您觉 ...
- 网易云api访问登录后仍返回{msg: ‘需要登录‘, code: 301}
网易云api访问登录后仍返回{msg: '需要登录', code: 301} 在用网易云API做网页时,需要使用某些需要登录的接口,在登录后仍然无法获取相关数据. 原因:在跨域请求时,没有携带用户凭证 ...
- nodejs typescript怎么发送get、post请求,如何获取网易云通信token
nodejs typescript怎么发送get.post请求,如何获取网易云通信token yarn add jshashes yarn add superagent 检查语法 yarn lint ...
最新文章
- iptables防火墙(二)
- 转 Struct 和 Union区别 以及 对内存对齐方式的说明
- java string封装类_java中八种基本数据类型以及它们的封装类,String类型的一些理解...
- 解决Tomcat下IntelliJ IDEA报错java.lang.NoClassDefFoundError: javax/servlet/ServletContextListener
- linux之telnet命令使用
- C++安全方向:(二)2.1 base16编解码原理讲解
- 第一章 软件项目管理概述
- yii2框架随笔19
- mariadb启动时报错Job for mariadb.service failed because the control process exited with error code....
- link标签 rel=“ alternate“ 应用解析
- 【技术贴】解决vss中提交pdf下载打开空白乱码
- matlab拟合热敏电阻温度特性曲线,深度解析NTC热敏电阻进行对数分段曲线拟合的技术分析...
- 《NPDP 产品经理认证知识体系指南》读书笔记
- android 卡片消息,安卓QNotified 支持xml卡片QQ消息 - 陌路人博客
- c语言scan例子,SCAN和C-SCAN算法图解
- iOS锁屏控制音乐播放
- Python——基础语法
- anti-fraud-admin 反欺诈后台
- 2023每日发布行业及概念热点切换跟踪图!
- 黑客安全专家郭盛华:逃避僵尸网络恶意软件攻击的13种方法