当前位置: 首页 > 工具软件 > IM_Java > 使用案例 >

Java对接网易云信IM 即时通讯

赫连昕
2023-12-01

       对接网易云信IM即时通信首先要在网易云信开放平台创建应用,获取到 AppKey与APP_SECRET

详细步骤请参考开放平台:

创建应用 - 控制台 (163.com)

       拿到App Key 与 APP_SECRET 之后就可以正式的进行java对接网易云信了

     创建网易云信账号代码:

/**
     * 注册网易云信账号
     *
     * @param accid String类型 云信账号,必须保证唯一性。以此接口返回结果中的accid为准。
     * @param mobile String类型 用户手机号码,非中国大陆手机号码需要填写国家代码
     * @param nickName String类型 用户昵称
     *
     * @return JSONObject
     */
    public JSONObject createCommunicationUser(String accid, String mobile,String nickName) throws IOException {
        HttpClient httpClient = HttpClientBuilder.create().build();
        String url = "https://api.netease.im/nimserver/user/create.action";  /*服务地址: 网易云信 IM 服务端 API 的接入地址*/
        HttpPost httpPost = new HttpPost(url);
        String nonce = UUID.randomUUID().toString();           //随机数(最大长度 128 个字符)
        String curTime = String.valueOf((new Date()).getTime() / 1000L);   //当前 UTC 时间戳
        String appSecret = "云信平台获取到的 APP_SECRET";
        /*CheckSum:SHA1(AppSecret + Nonce + CurTime),将该三个参数拼接的字符串进行 SHA1 哈希计算从而生成 16 进制字符(类型为 String,小写)*/
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
        /*设置请求头*/
        httpPost.addHeader("AppKey", YxConfig.APP_KEY);   //云信平台获取的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<NameValuePair> nvps = new ArrayList<NameValuePair>();
        /*请求体*/
        nvps.add(new BasicNameValuePair("accid", accid));
        nvps.add(new BasicNameValuePair("mobile", mobile));
        nvps.add(new BasicNameValuePair("name", nickName));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        HttpResponse response = httpClient.execute(httpPost);
        JSONObject existJsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
        return existJsonObject;
    }

 计算CheckSum的代码如下

import java.security.MessageDigest;

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' };
}

   在App用户进行注册的时候调用 createCommunicationUser方法 返回一个JSON,解析该JSON并将返回的accid与token存到数据库中,在客户端需要用户的accid与token。

/*获取到accid使用MD5加密方式*/
 String accid = Md5Utils.hash(String.valueOf(new Date().getTime()) + "HL" + new Random().nextFloat());
 JSONObject communicationUser = createCommunicationUser(accid, phone,"用户昵称");
            /*在json字符串中解析返回的accid与token存到数据库中*/
 /*user为用户的实体类*/
 user.setAccid(communicationUser.getJSONObject("info").get("accid").toString());
 user.setImToken(communicationUser.getJSONObject("info").get("token").toString());

MD5Utils:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

/**
 * Md5加密方法
 *
 * @author ruoyi
 */
public class Md5Utils
{
    private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);

    private static byte[] md5(String s)
    {
        MessageDigest algorithm;
        try
        {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes("UTF-8"));
            byte[] messageDigest = algorithm.digest();
            return messageDigest;
        }
        catch (Exception e)
        {
            log.error("MD5 Error...", e);
        }
        return null;
    }

    private static final String toHex(byte hash[])
    {
        if (hash == null)
        {
            return null;
        }
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++)
        {
            if ((hash[i] & 0xff) < 0x10)
            {
                buf.append("0");
            }
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    public static String hash(String s)
    {
        try
        {
            return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
        }
        catch (Exception e)
        {
            log.error("not supported charset...{}", e);
            return s;
        }
    }
}

 更新网易云信token,在用户重新登录时更新token,并将数据库中的token更新

 /**
     * 更新网易云信token
     */
    public JSONObject updateCommunicationUserToken(String userAccid) throws IOException {

        HttpClient httpClient = HttpClientBuilder.create().build();
        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);
        String appSecret = YxConfig.APP_SECRET;
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);

        httpPost.addHeader("AppKey", YxConfig.APP_KEY);
        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<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", userAccid));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
        HttpResponse response = httpClient.execute(httpPost);
        JSONObject existJsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity(), "utf-8"));
        return existJsonObject;
    }

至此java对接网易云信token完成!!!!!

 类似资料: