1. 程式人生 > >Java接入網易雲信工具類

Java接入網易雲信工具類

package com.xinluo.app.common.netease;

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<NameValuePair> nvps = new ArrayList<NameValuePair>();
        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<NameValuePair> nvps = new ArrayList<NameValuePair>();
        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失敗");
    }
}

接入網易雲信過程,記錄下