当前位置:   article > 正文

JAVA集成腾讯云即时通讯IM服务端_java如何整合 腾讯im

java如何整合 腾讯im

一. 腾讯IM快速入门
1. 注册腾讯云账号,找到即时通信IM控制台
腾讯IM控制台:登录 - 腾讯云

2. 创建即时通信应用

watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA6JCM5pif5Lq6,size_20,color_FFFFFF,t_70,g_se,x_16
3. 进到应用里面可以看到这个应用的SDKAppID和key(密钥)

 watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA6JCM5pif5Lq6,size_20,color_FFFFFF,t_70,g_se,x_16


4. 可以参考官方提供的“服务端API接口文档”和“接口调试工具”
API接口文档:https://cloud.tencent.com/document/product/269
接口在线调试工具:https://tcc.tencentcs.com/im-api-tool/index.html
二. 基于Java对一些方法的简单封装
注:封装的方法覆盖得肯定不全面,可以根据自身需求在此基础上补充

1. 配置文件
#腾讯im相关配置

  1. silence.tencent.cloud.im.sdkAppId=应用SDKAppId
  2. silence.tencent.cloud.im.key=应用Key


2. 腾讯im相关API接口常量类TencentCloudImApiConstant.java

  1. public class TencentCloudImApiConstant {
  2.     /**
  3.      * 账号管理
  4.      */
  5.     public static class AccountManage {
  6.         /**导入单个帐号*/
  7.         public static final String ACCOUNT_IMPORT = "v4/im_open_login_svc/account_import";
  8.         /**导入多个帐号*/
  9.         public static final String MULTI_ACCOUNT_IMPORT = "v4/im_open_login_svc/account_import";
  10.         /**删除帐号*/
  11.         public static final String ACCOUNT_DELETE = "v4/im_open_login_svc/account_delete";
  12.         /**查询帐号*/
  13.         public static final String ACCOUNT_CHECK = "v4/im_open_login_svc/account_check";
  14.         /**失效帐号登录状态*/
  15.         public static final String ACCOUNT_KICK = "v4/im_open_login_svc/kick";
  16.         /**查询账号在线状态*/
  17.         public static final String ACCOUNT_QUERY_STATE = "v4/openim/querystate";
  18.     }
  19.     /**
  20.      * 单聊消息
  21.      */
  22.     public static class SingleChatManage {
  23.         /**单发单聊消息*/
  24.         public static final String SEND_MSG = "v4/openim/sendmsg";
  25.         /**批量发单聊消息*/
  26.         public static final String BATCH_SEND_MSG = "v4/openim/batchsendmsg";
  27.         /**导入单聊消息*/
  28.         public static final String IMPORT_MSG = "v4/openim/importmsg";
  29.         /**查询单聊消息*/
  30.         public static final String ADMIN_GET_ROAM_MSG = "v4/openim/admin_getroammsg";
  31.         /**撤回单聊消息*/
  32.         public static final String ADMIN_MSG_WITH_DRAW = "v4/openim/admin_msgwithdraw";
  33.         /**设置单聊消息已读*/
  34.         public static final String ADMIN_SET_MSG_READ = "v4/openim/admin_set_msg_read";
  35.     }
  36.     /**
  37.      * 全员推送
  38.      */
  39.     public static class AllPushManage {
  40.         /**全员推送*/
  41.         public static final String IM_PUSH = "v4/all_member_push/im_push";
  42.         /**设置应用属性名称*/
  43.         public static final String IM_SET_ATTR_NAME = "v4/all_member_push/im_set_attr_name";
  44.         /**获取应用属性名称*/
  45.         public static final String IM_GET_ATTR_NAME = "v4/all_member_push/im_get_attr_name";
  46.         /**获取用户属性*/
  47.         public static final String IM_GET_ATTR = "v4/all_member_push/im_get_attr";
  48.         /**设置用户属性*/
  49.         public static final String IM_SET_ATTR = "v4/all_member_push/im_set_attr";
  50.         /**删除用户属性*/
  51.         public static final String IM_REMOVE_ATTR = "v4/all_member_push/im_remove_attr";
  52.         /**获取用户标签*/
  53.         public static final String IM_GET_TAG = "v4/all_member_push/im_get_tag";
  54.         /**添加用户标签*/
  55.         public static final String IM_ADD_TAG = "v4/all_member_push/im_add_tag";
  56.         /**删除用户标签*/
  57.         public static final String IM_REMOVE_TAG = "v4/all_member_push/im_remove_tag";
  58.         /**删除用户所有标签*/
  59.         public static final String IM_REMOVE_ALL_TAGS = "v4/all_member_push/im_remove_all_tags";
  60.     }
  61.     /**
  62.      * 资料管理
  63.      */
  64.     public static class PortraitManage {
  65.         /**设置资料*/
  66.         public static final String PORTRAIT_SET = "v4/profile/portrait_set";
  67.         /**拉取资料*/
  68.         public static final String PORTRAIT_GET = "v4/profile/portrait_get";
  69.     }
  70.     /**
  71.      * 关系链管理
  72.      */
  73.     public static class RelationManage {
  74.         /**添加好友*/
  75.         public static final String FRIEND_ADD = "v4/sns/friend_add";
  76.         /**导入好友*/
  77.         public static final String FRIEND_IMPORT = "v4/sns/friend_import";
  78.         /**更新好友*/
  79.         public static final String FRIEND_UPDATE = "v4/sns/friend_update";
  80.         /**删除好友*/
  81.         public static final String FRIEND_DELETE = "v4/sns/friend_delete";
  82.         /**删除所有好友*/
  83.         public static final String FRIEND_DELETE_ALL = "v4/sns/friend_delete_all";
  84.         /**校验好友*/
  85.         public static final String FRIEND_CHECK = "v4/sns/friend_check";
  86.         /**拉取好友*/
  87.         public static final String FRIEND_GET = "v4/sns/friend_get";
  88.         /**拉取指定好友*/
  89.         public static final String FRIEND_GET_LIST = "v4/sns/friend_get_list";
  90.         /**添加黑名单*/
  91.         public static final String BLACK_LIST_ADD = "v4/sns/black_list_add";
  92.         /**删除黑名单*/
  93.         public static final String BLACK_LIST_DELETE = "v4/sns/black_list_delete";
  94.         /**拉取黑名单*/
  95.         public static final String BLACK_LIST_GET = "v4/sns/black_list_get";
  96.         /**校验黑名单*/
  97.         public static final String BLACK_LIST_CHECK = "v4/sns/black_list_check";
  98.         /**添加分组*/
  99.         public static final String GROUP_ADD = "v4/sns/group_add";
  100.         /**删除分组*/
  101.         public static final String GROUP_DELETE = "v4/sns/group_delete";
  102.         /**拉取分组*/
  103.         public static final String GROUP_GET = "v4/sns/group_get";
  104.     }
  105.     /**
  106.      * 群组管理
  107.      */
  108.     public static class GroupManage {
  109.         /**创建群组*/
  110.         public static final String CREATE_GROUP = "v4/group_open_http_svc/create_group";
  111.         /**获取群详细资料*/
  112.         public static final String GET_GROUP_INFO = "v4/group_open_http_svc/get_group_info";
  113.         /**获取群成员详细资料*/
  114.         public static final String GET_GROUP_MEMBER_INFO = "v4/group_open_http_svc/get_group_member_info";
  115.         /**修改群基础资料*/
  116.         public static final String MODIFY_GROUP_BASE_INFO = "v4/group_open_http_svc/modify_group_base_info";
  117.         /**增加群成员*/
  118.         public static final String ADD_GROUP_MEMBER = "v4/group_open_http_svc/add_group_member";
  119.         /**删除群成员*/
  120.         public static final String DELETE_GROUP_MEMBER = "v4/group_open_http_svc/delete_group_member";
  121.         /**修改群成员资料*/
  122.         public static final String MODIFY_GROUP_MEMBER_INFO = "v4/group_open_http_svc/modify_group_member_info";
  123.         /**解散群组*/
  124.         public static final String DESTROY_GROUP = "v4/group_open_http_svc/destroy_group";
  125.         /**获取用户所加入的群组*/
  126.         public static final String GET_JOINED_GROUP_LIST = "v4/group_open_http_svc/get_joined_group_list";
  127.         /**查询用户在群组中的身份*/
  128.         public static final String GET_ROLE_IN_GROUP = "v4/group_open_http_svc/get_role_in_group";
  129.         /**批量禁言和取消禁言*/
  130.         public static final String FORBID_SEND_MSG = "v4/group_open_http_svc/forbid_send_msg";
  131.         /**获取被禁言群成员列表*/
  132.         public static final String GET_GROUP_SHUT_UIN = "v4/group_open_http_svc/get_group_shutted_uin";
  133.         /**在群组中发送普通消息*/
  134.         public static final String SEND_GROUP_MSG = "v4/group_open_http_svc/send_group_msg";
  135.         /**在群组中发送系统通知*/
  136.         public static final String SEND_GROUP_SYSTEM_NOTIFICATION = "v4/group_open_http_svc/send_group_system_notification";
  137.         /**撤回群消息*/
  138.         public static final String GROUP_MSG_RECALL = "v4/group_open_http_svc/group_msg_recall";
  139.         /**转让群主*/
  140.         public static final String CHANGE_GROUP_OWNER = "v4/group_open_http_svc/change_group_owner";
  141.         /**导入群基础资料*/
  142.         public static final String IMPORT_GROUP = "v4/group_open_http_svc/import_group";
  143.         /**导入群消息*/
  144.         public static final String IMPORT_GROUP_MSG = "v4/group_open_http_svc/import_group_msg";
  145.         /**导入群成员*/
  146.         public static final String IMPORT_GROUP_MEMBER = "v4/group_open_http_svc/import_group_member";
  147.         /**设置成员未读消息计数*/
  148.         public static final String SET_UNREAD_MSG_NUM = "v4/group_open_http_svc/set_unread_msg_num";
  149.         /**删除指定用户发送的消息*/
  150.         public static final String DELETE_GROUP_MSG_BY_SENDER = "v4/group_open_http_svc/delete_group_msg_by_sender";
  151.         /**拉取群历史消息*/
  152.         public static final String GROUP_MSG_GET_SIMPLE = "v4/group_open_http_svc/group_msg_get_simple";
  153.         /**获取直播群在线人数*/
  154.         public static final String GET_ONLINE_MEMBER_NUM = "v4/group_open_http_svc/get_online_member_num";
  155.     }
  156.     /**
  157.      * 全局禁言管理
  158.      */
  159.     public static class AllSinentManage {
  160.         /**设置全局禁言*/
  161.         public static final String SET_NO_SPEAKING = "v4/openconfigsvr/setnospeaking";
  162.         /**查询全局禁言*/
  163.         public static final String GET_NO_SPEAKING = "v4/openconfigsvr/getnospeaking";
  164.     }
  165.     /**
  166.      * 运营管理
  167.      */
  168.     public static class OperationManage {
  169.         /**拉取运营数据*/
  170.         public static final String GET_APP_INFO = "v4/openconfigsvr/getappinfo";
  171.         /**下载消息记录*/
  172.         public static final String GET_HISTORY = "v4/open_msg_svc/get_history";
  173.         /**获取服务器 IP 地址*/
  174.         public static final String GET_IP_LIST = "v4/ConfigSvc/GetIPList";
  175.     }
  176. }


3. 腾讯im相关常量类TencentCloudImConstant.java

  1. public class TencentCloudImConstant {
  2.     /**
  3.      * IM请求处理结果
  4.      */
  5.     public final static String ACTION_STATUS_OK = "OK";
  6.     public final static String ACTION_STATUS_FAIL = "FAIL";
  7.     /**
  8.      * IM发消息是否同步到发送方(1-同步,2-不同步)
  9.      */
  10.     public final static Integer SYNC_OTHER_MACHINE_YES = 1;
  11.     public final static Integer SYNC_OTHER_MACHINE_NO = 2;
  12.     /**
  13.      * IM消息对象类型:
  14.      * TIMTextElem    文本消息。
  15.      * TIMLocationElem    地理位置消息。
  16.      * TIMFaceElem    表情消息。
  17.      * TIMCustomElem    自定义消息,当接收方为 iOS 系统且应用处在后台时,此消息类型可携带除文本以外的字段到 APNs。一条组合消息中只能包含一个 TIMCustomElem 自定义消息元素。
  18.      * TIMSoundElem    语音消息。
  19.      * TIMImageElem    图像消息。
  20.      * TIMFileElem    文件消息。
  21.      * TIMVideoFileElem    视频消息。
  22.      */
  23.     public final static String TIM_TEXT_ELEM = "TIMTextElem";
  24.     public final static String TIM_LOCATION_ELEM = "TIMLocationElem";
  25.     public final static String TIM_FACE_ELEM = "TIMFaceElem";
  26.     public final static String TIM_CUSTOM_ELEM = "TIMCustomElem";
  27.     public final static String TIM_SOUND_ELEM = "TIMSoundElem";
  28.     public final static String TIM_IMAGE_ELEM = "TIMImageElem";
  29.     public final static String TIM_FILE_ELEM = "TIMFileElem";
  30.     public final static String TIM_VIDEOFILE_ELEM = "TIMVideoFileElem";
  31.     /**
  32.      * 微信响应消息类型
  33.      * WX_MSG_TYPE_EVENT:事件类型,事件类型对应"user_enter_tempsession"表示建立会话
  34.      * WX_MSG_TYPE_TEXT:文本类型
  35.      * WX_MSG_TYPE_TEXT:图片类型
  36.      * WX_MSG_TYPE_TEXT:小程序卡片
  37.      */
  38.     public final static String WX_MSG_TYPE_EVENT = "event";
  39.     public final static String WX_MSG_TYPE_TEXT = "text";
  40.     public final static String WX_MSG_TYPE_IMAGE = "image";
  41.     public final static String WX_MSG_TYPE_APPLET_CARD = "miniprogrampage";
  42. }


4. 发送http请求工具类HttpUtil.java

  1. import com.alibaba.fastjson.JSONObject;
  2. import org.apache.http.Consts;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.entity.UrlEncodedFormEntity;
  8. import org.apache.http.client.methods.CloseableHttpResponse;
  9. import org.apache.http.client.methods.HttpGet;
  10. import org.apache.http.client.methods.HttpPost;
  11. import org.apache.http.entity.StringEntity;
  12. import org.apache.http.impl.client.CloseableHttpClient;
  13. import org.apache.http.impl.client.DefaultHttpClient;
  14. import org.apache.http.impl.client.HttpClients;
  15. import org.apache.http.message.BasicNameValuePair;
  16. import org.apache.http.util.EntityUtils;
  17. import java.io.IOException;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. import java.util.Map;
  21. public class HttpUtil {
  22.     private static final CloseableHttpClient httpclient = HttpClients.createDefault();
  23.     /**
  24.      * 发送HttpGet请求
  25.      * @param url
  26.      * @return
  27.      */
  28.     public static String sendGet(String url) {
  29.         HttpGet httpget = new HttpGet(url);
  30.         CloseableHttpResponse response = null;
  31.         try {
  32.             response = httpclient.execute(httpget);
  33.         } catch (IOException e1) {
  34.             e1.printStackTrace();
  35.         }
  36.         String result = null;
  37.         try {
  38.             HttpEntity entity = response.getEntity();
  39.             if (entity != null) {
  40.                 result = EntityUtils.toString(entity);
  41.             }
  42.         } catch (Exception e) {
  43.             e.printStackTrace();
  44.         } finally {
  45.             try {
  46.                 response.close();
  47.             } catch (IOException e) {
  48.                 e.printStackTrace();
  49.             }
  50.         }
  51.         return result;
  52.     }
  53.     /**
  54.      * 发送HttpPost请求,参数为map
  55.      * @param url
  56.      * @param map
  57.      * @return
  58.      */
  59.     public static String sendPost(String url, Map<String, String> map) {
  60.         List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  61.         for (Map.Entry<String, String> entry : map.entrySet()) {
  62.             formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  63.         }
  64.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
  65.         HttpPost httppost = new HttpPost(url);
  66.         httppost.setEntity(entity);
  67.         CloseableHttpResponse response = null;
  68.         try {
  69.             response = httpclient.execute(httppost);
  70.         } catch (IOException e) {
  71.             e.printStackTrace();
  72.         }
  73.         HttpEntity entity1 = response.getEntity();
  74.         String result = null;
  75.         try {
  76.             result = EntityUtils.toString(entity1);
  77.         } catch (Exception e) {
  78.             e.printStackTrace();
  79.         }
  80.         return result;
  81.     }
  82.     /**
  83.      * 发送不带参数的HttpPost请求
  84.      * @param url
  85.      * @return
  86.      */
  87.     public static String sendPost(String url) {
  88.         HttpPost httppost = new HttpPost(url);
  89.         CloseableHttpResponse response = null;
  90.         try {
  91.             response = httpclient.execute(httppost);
  92.         } catch (IOException e) {
  93.             e.printStackTrace();
  94.         }
  95.         HttpEntity entity = response.getEntity();
  96.         String result = null;
  97.         try {
  98.             result = EntityUtils.toString(entity);
  99.         } catch (Exception e) {
  100.             e.printStackTrace();
  101.         }
  102.         return result;
  103.     }
  104.     public static String doPost2(String url, JSONObject param) {
  105.         HttpPost httpPost = null;
  106.         String result = null;
  107.         try {
  108.             HttpClient client = new DefaultHttpClient();
  109.             httpPost = new HttpPost(url);
  110.             if (param != null) {
  111.                 StringEntity se = new StringEntity(param.toString(), "utf-8");
  112.                 httpPost.setEntity(se); // post方法中,加入json数据
  113.                 httpPost.setHeader("Content-Type", "application/json");
  114.                 httpPost.setHeader("Authorization", param.getString("authorization"));
  115.             }
  116.             HttpResponse response = client.execute(httpPost);
  117.             if (response != null) {
  118.                 HttpEntity resEntity = response.getEntity();
  119.                 if (resEntity != null) {
  120.                     result = EntityUtils.toString(resEntity, "utf-8");
  121.                 }
  122.             }
  123.         } catch (Exception ex) {
  124.             ex.printStackTrace();
  125.         }
  126.         return result;
  127.     }
  128. }


5. 腾讯im常用方法工具类TencentCloudImUtil.java

  1. import com.alibaba.fastjson.JSONObject;
  2. import com.example.tencentcloudim.constant.TencentCloudImApiConstant;
  3. import com.example.tencentcloudim.constant.TencentCloudImConstant;
  4. import com.tencentyun.TLSSigAPIv2;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.apache.commons.lang3.RandomUtils;
  7. import org.apache.commons.lang3.StringUtils;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.stereotype.Component;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. import java.util.stream.Collectors;
  14. @Slf4j
  15. @Component
  16. public class TencentCloudImUtil {
  17.     private static final String HTTPS_URL_PREFIX = "https://console.tim.qq.com/";
  18.     private static final String APP_MANAGER = "administrator";
  19.     private static final String REDIS_IM_USER_SIG = "silence:im_user_sig:";
  20.     @Value("${silence.tencent.cloud.im.sdkAppId}")
  21.     private long sdkAppId;
  22.     @Value("${silence.tencent.cloud.im.key}")
  23.     private String key;
  24.     @Autowired
  25.     private RedisServiceUtil redisServiceUtil;
  26.     /**
  27.      * 获取腾讯云用户签名
  28.      */
  29.     public String getTxCloudUserSig() {
  30.         String userSig = redisServiceUtil.get(REDIS_IM_USER_SIG + APP_MANAGER);
  31.         if (StringUtils.isEmpty(userSig)) {
  32.             TLSSigAPIv2 tlsSigApi = new TLSSigAPIv2(sdkAppId, key);
  33.             userSig = tlsSigApi.genUserSig(APP_MANAGER, 86400);
  34.             redisServiceUtil.set(REDIS_IM_USER_SIG + APP_MANAGER, userSig, 86400L);
  35.         }
  36.         return userSig;
  37.     }
  38.     /**
  39.      * 获取腾讯im请求路径
  40.      */
  41.     private String getHttpsUrl(String imServiceApi, Integer random) {
  42.         return String.format("%s%s?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json",
  43.                 HTTPS_URL_PREFIX, imServiceApi, sdkAppId, APP_MANAGER, this.getTxCloudUserSig(), random);
  44.     }
  45.     /**
  46.      * 导入单个账号
  47.      * @param userId 用户id
  48.      */
  49.     public void accountImport(String userId) {
  50.         accountImport(userId, null);
  51.     }
  52.     public void accountImport(String userId, String userName) {
  53.         accountImport(userId, userName, null);
  54.     }
  55.     public void accountImport(String userId, String userName, String faceUrl) {
  56.         Integer random = RandomUtils.nextInt(0, 999999999);
  57.         String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_IMPORT, random);
  58.         JSONObject jsonObject = new JSONObject();
  59.         jsonObject.put("Identifier", userId);
  60.         if (StringUtils.isNotEmpty(userName)) {
  61.             jsonObject.put("Nick", userName);
  62.         }
  63.         if (StringUtils.isNotEmpty(faceUrl)) {
  64.             jsonObject.put("FaceUrl", faceUrl);
  65.         }
  66.         log.info("腾讯云im导入单个账号,请求参数:{}", jsonObject.toString());
  67.         String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  68.         log.info("腾讯云im导入单个账号,返回结果:{}", result);
  69.     }
  70.     /**
  71.      * 导入多个账号
  72.      * @param userIds 用户id集合
  73.      */
  74.     public void multiAccountImport(List<String> userIds) {
  75.         Integer random = RandomUtils.nextInt(0, 999999999);
  76.         String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.MULTI_ACCOUNT_IMPORT, random);
  77.         JSONObject jsonObject = new JSONObject();
  78.         jsonObject.put("Accounts", userIds);
  79.         log.info("腾讯云im导入多个账号,请求参数:{}", jsonObject.toString());
  80.         String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  81.         log.info("腾讯云im导入单个账户,返回结果:{}", result);
  82.     }
  83.     /**
  84.      * 删除账号
  85.      * @param userIds 用户id集合
  86.      */
  87.     public void accountDelete(List<String> userIds) {
  88.         Integer random = RandomUtils.nextInt(0, 999999999);
  89.         String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_DELETE, random);
  90.         JSONObject jsonObject = new JSONObject();
  91.         jsonObject.put("DeleteItem", getUserIdJsonList(userIds));
  92.         log.info("腾讯云im删除账号,请求参数:{}", jsonObject.toString());
  93.         String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  94.         log.info("腾讯云im删除账户,返回结果:{}", result);
  95.     }
  96.     /**
  97.      * 查询账号是否已经导入im
  98.      * @param userIds 用户id集合
  99.      */
  100.     public String accountCheck(List<String> userIds) {
  101.         Integer random = RandomUtils.nextInt(0, 999999999);
  102.         String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_CHECK, random);
  103.         JSONObject jsonObject = new JSONObject();
  104.         jsonObject.put("CheckItem", getUserIdJsonList(userIds));
  105.         log.info("腾讯云im查询账号,请求参数:{}", jsonObject.toString());
  106.         String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  107.         log.info("腾讯云im查询账号,返回结果:{}", result);
  108.         return result;
  109.     }
  110.     private List<JSONObject> getUserIdJsonList(List<String> userIds) {
  111.         return userIds.stream().map(v -> {
  112.             JSONObject userIdJson = new JSONObject();
  113.             userIdJson.put("UserID", v);
  114.             return userIdJson;
  115.         }).collect(Collectors.toList());
  116.     }
  117.     /**
  118.      * 单发单聊消息
  119.      * @param syncOtherMachine 是否同步消息到发送方(1-同步,2-不同步)
  120.      * @param fromUserId 发送方用户id
  121.      * @param toUserId 接收方用户id
  122.      * @param msgType 消息对象类型
  123.      * @param msgContent 消息内容
  124.      */
  125.     public String sendMsg(Integer syncOtherMachine, String fromUserId, String toUserId, String msgType, String msgContent) {
  126.         Integer random = RandomUtils.nextInt(0, 999999999);
  127.         String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.SEND_MSG, random);
  128.         JSONObject jsonObject = new JSONObject();
  129.         jsonObject.put("SyncOtherMachine", syncOtherMachine);
  130.         if (StringUtils.isNotEmpty(fromUserId)) {
  131.             // 发送方不为空表示指定发送用户,为空表示为管理员发送消息
  132.             jsonObject.put("From_Account", fromUserId);
  133.         }
  134.         jsonObject.put("To_Account", toUserId);
  135.         jsonObject.put("MsgRandom", random);
  136.         List<JSONObject> msgBody = getMsgBody(msgType, msgContent);
  137.         jsonObject.put("MsgBody", msgBody);
  138.         log.info("腾讯云im单发单聊消息,请求参数:{}", jsonObject.toString());
  139.         String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  140.         log.info("腾讯云im单发单聊消息,返回结果:{}", result);
  141.         return result;
  142.     }
  143.     /**
  144.      * 批量发单聊消息
  145.      * @param syncOtherMachine 是否同步消息到发送方(1-同步,2-不同步)
  146.      * @param fromUserId 发送方用户id
  147.      * @param toUserIds 接收方用户id集合
  148.      * @param msgType 消息对象类型
  149.      * @param msgContent 消息内容
  150.      */
  151.     public String batchSendMsg(Integer syncOtherMachine, String fromUserId, List<String> toUserIds, String msgType, String msgContent) {
  152.         Integer random = RandomUtils.nextInt(0, 999999999);
  153.         String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.BATCH_SEND_MSG, random);
  154.         JSONObject jsonObject = new JSONObject();
  155.         jsonObject.put("SyncOtherMachine", syncOtherMachine);
  156.         if (StringUtils.isNotEmpty(fromUserId)) {
  157.             // 发送方不为空表示指定发送用户,为空表示为管理员发送消息
  158.             jsonObject.put("From_Account", fromUserId);
  159.         }
  160.         jsonObject.put("To_Account", toUserIds);
  161.         jsonObject.put("MsgRandom", random);
  162.         List<JSONObject> msgBody = getMsgBody(msgType, msgContent);
  163.         jsonObject.put("MsgBody", msgBody);
  164.         log.info("腾讯云im批量发单聊消息,请求参数:{}", jsonObject.toString());
  165.         String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  166.         log.info("腾讯云im批量发单聊消息,返回结果:{}", result);
  167.         return result;
  168.     }
  169.     /**
  170.      * 拼接发送消息内容
  171.      * @param msgType 消息类型
  172.      * @param msgContent 发送消息内容
  173.      * @return 消息内容
  174.      */
  175.     private List<JSONObject> getMsgBody(String msgType, String msgContent) {
  176.         List<JSONObject> msgBody = new ArrayList<>();
  177.         if (msgType.equals(TencentCloudImConstant.TIM_TEXT_ELEM)) {
  178.             // 文本类型
  179.             JSONObject msgBodyJson = new JSONObject();
  180.             msgBodyJson.put("MsgType", msgType);
  181.             JSONObject msgContentObj = new JSONObject();
  182.             msgContentObj.put("Text", msgContent);
  183.             msgBodyJson.put("MsgContent", msgContentObj);
  184.             msgBody.add(msgBodyJson);
  185.         }
  186.         return msgBody;
  187.     }
  188.     /**
  189.      * 查询单聊消息
  190.      * @param fromUserId 发送方用户id
  191.      * @param toUserId 接收方用户id
  192.      * @param maxCnt 查询条数
  193.      * @param startTime 起始时间(单位:秒)
  194.      * @param endTime 结束时间(单位:秒)
  195.      * @param lastMsgKey 最后一条消息的 MsgKey
  196.      * @return 单聊消息列表
  197.      */
  198.     public String adminGetRoamMsg(String fromUserId, String toUserId, Integer maxCnt, Long startTime, Long endTime, String lastMsgKey) {
  199.         Integer random = RandomUtils.nextInt(0, 999999999);
  200.         String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_GET_ROAM_MSG, random);
  201.         JSONObject jsonObject = new JSONObject();
  202.         jsonObject.put("From_Account", fromUserId);
  203.         jsonObject.put("To_Account", toUserId);
  204.         jsonObject.put("MaxCnt", maxCnt);
  205.         jsonObject.put("MinTime", startTime);
  206.         jsonObject.put("MaxTime", endTime);
  207.         if (StringUtils.isNotEmpty(lastMsgKey)){
  208.             jsonObject.put("LastMsgKey", lastMsgKey);
  209.         }
  210.         log.info("腾讯云im查询单聊消息,请求参数:{}", jsonObject.toString());
  211.         String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  212.         log.info("腾讯云im查询单聊消息,返回结果:{}", result);
  213.         return result;
  214.     }
  215.     /**
  216.      * 撤回单聊消息
  217.      * @param fromUserId 发送方用户id
  218.      * @param toUserId 接收方用户id
  219.      * @param msgKey MsgKey
  220.      */
  221.     public void adminMsgWithDraw(String fromUserId, String toUserId, String msgKey) {
  222.         Integer random = RandomUtils.nextInt(0, 999999999);
  223.         String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_MSG_WITH_DRAW, random);
  224.         JSONObject jsonObject = new JSONObject();
  225.         jsonObject.put("From_Account", fromUserId);
  226.         jsonObject.put("To_Account", toUserId);
  227.         jsonObject.put("MsgKey", msgKey);
  228.         log.info("腾讯云im撤回单聊消息,请求参数:{}", jsonObject.toString());
  229.         String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  230.         log.info("腾讯云im撤回单聊消息,返回结果:{}", result);
  231.     }
  232.     /**
  233.      * 设置单聊消息已读
  234.      * @param reportUserId 读取消息的用户
  235.      * @param peerUserId 发送消息的用户
  236.      */
  237.     public void adminSetMsgRead(String reportUserId, String peerUserId) {
  238.         Integer random = RandomUtils.nextInt(0, 999999999);
  239.         String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_SET_MSG_READ, random);
  240.         JSONObject jsonObject = new JSONObject();
  241.         jsonObject.put("Report_Account", reportUserId);
  242.         jsonObject.put("Peer_Account", peerUserId);
  243.         log.info("腾讯云im设置单聊消息已读,请求参数:{}", jsonObject.toString());
  244.         String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  245.         log.info("腾讯云im设置单聊消息已读,返回结果:{}", result);
  246.     }
  247. }

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/178587
推荐阅读
相关标签
  

闽ICP备14008679号