创建环信群组——Java发送http get/post请求,调用接口/方法

本文介绍如何使用环信API创建群组,并通过POST请求实现与服务器的数据交互。主要内容涵盖环信群组创建流程及所需参数说明,同时提供了一个具体的POST请求工具类示例。

POST请求工具类:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

/**
 * 发送post请求
 * @author Administrator
 *
 */
public class HttpTool {

 /**
  * 发送post请求
  *
  * @param params
  *            参数
  * @param requestUrl
  *            请求地址
  * @param authorization
  *            授权书
  * @param body
  *        请求体:Request Body
  * @return 返回结果
  * @throws IOException
  */
 @SuppressWarnings("deprecation")
 public static String sendPost(String params, String body, String requestUrl, String authorization) throws IOException {

  byte[] requestBytes = params.getBytes("utf-8"); // 将参数转为二进制流
  HttpClient httpClient = new HttpClient();// 客户端实例化
  PostMethod postMethod = new PostMethod(requestUrl);
  // 设置请求头Authorization
  postMethod.setRequestHeader("Authorization", "Bearer " + authorization);
  // 设置请求头 Content-Type
  postMethod.setRequestHeader("Content-Type", "application/json");
  InputStream inputStream = new ByteArrayInputStream(requestBytes, 0, requestBytes.length);
  RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, requestBytes.length,
    "application/json; charset=utf-8"); // 请求体
 
  postMethod.setRequestEntity(requestEntity);
  
  postMethod.setRequestBody(body);//请求Body
//  postMethod.setRequestBody(parametersBody);//请求Body
  
  httpClient.executeMethod(postMethod);// 执行请求
  InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流
  byte[] datas = null;
  try {
   datas = readInputStream(soapResponseStream);// 从输入流中读取数据
  } catch (Exception e) {
   e.printStackTrace();
  }
  String result = new String(datas, "UTF-8");// 将二进制流转为String
  // 打印返回结果
  // System.out.println(result);

  return result;

 }

 /**
  * 从输入流中读取数据
  *
  * @param inStream
  * @return
  * @throws Exception
  */
 public static byte[] readInputStream(InputStream inStream) throws Exception {
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len = 0;
  while ((len = inStream.read(buffer)) != -1) {
   outStream.write(buffer, 0, len);
  }
  byte[] data = outStream.toByteArray();
  outStream.close();
  inStream.close();
  return data;
 }

}

 

 

************************************************************************************************************************************************

private static String API_PROTOCAL = null;
 private static String API_HOST = null;
 private static String API_ORG = null;
 private static String API_APP = null;

创建环信群组代码片段:

String requestUrl = null;//请求路径
    String params = ""; //参数
    String body = null;//请求body
    String authorization = null;//授权 token
    String members = "";
    /**
     * 1.请求路径
     */
    try {
     //创建一个Properties容器
     Properties prop = new Properties();
     //从流中加载properties文件信息
     InputStream in = CountryDoctorRegisterServiceImpl.class.getClassLoader().getResourceAsStream("config.properties");
     prop.load(in);
     API_PROTOCAL = prop.getProperty("API_PROTOCAL");//https请求协议
     API_HOST = prop.getProperty("API_HOST");//环信请求域名
     API_ORG = prop.getProperty("API_ORG");//企业的唯一标识,开发者在环信开发者管理后台注册账号时填写的企业 ID
     API_APP = prop.getProperty("API_APP");//同一“企业”下“APP”唯一标识,开发者在环信开发者管理后台创建应用时填写的“应用名称”

     // https://a1.easemob.com/{org_name}/{app_name}/chatgroups
     requestUrl = API_PROTOCAL +"://"+ API_HOST + "/" + API_ORG + "/" + API_APP + "/" + "chatgroups";
     System.out.println(requestUrl);
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    
    
    
    /**
     * 2.创建请求
     * Request Body:
     * {
     *   "groupname":"testrestgrp12", //群组名称,此属性为必须的
     *   "desc":"server create group", //群组描述,此属性为必须的
     *   "public":true, //是否是公开群,此属性为必须的
     *   "maxusers":300, //群组成员最大数(包括群主),值为数值类型,默认值200,最大值2000,此属性为可选的
     *   "members_only":true // 加入群是否需要群主或者群管理员审批,默认是false
     *   "allowinvites": true  //是否允许群成员邀请别人加入此群。 true:允许群成员邀请人加入此群,false:只有群主或者管理员才可以往群里加人。
     *   "owner":"jma1", //群组的管理员,此属性为必须的
     *   "members":["jma2","jma3"] //群组成员,此属性为可选的,但是如果加了此项,数组元素至少一个(注:群主jma1不需要写入到members里面)
     * }
     */
    
    //截取群组成员
    String[] split = members.split(",");
    
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    
    String groupname = "test" + sdf.format(new Date());
    
    Map<String,Object> bodyMap = new HashMap<String,Object>();
    bodyMap.put("groupname", groupname);//群组名称,此属性为必须的
    bodyMap.put("desc", "desc");//群组描述,此属性为必须的
    bodyMap.put("public", true);//是否是公开群,此属性为必须的
    bodyMap.put("maxusers", 200);//群组成员最大数(包括群主),值为数值类型,默认值200,最大值2000,此属性为可选的
    bodyMap.put("members_only", false);// 加入群是否需要群主或者群管理员审批,默认是false
    bodyMap.put("allowinvites", false);//是否允许群成员邀请别人加入此群。 true:允许群成员邀请人加入此群,false:只有群主或者管理员才可以往群里加人。
    bodyMap.put("owner", "owner");//群组的管理员,此属性为必须的
    bodyMap.put("members", split);//群组成员,此属性为可选的,但是如果加了此项,数组元素至少一个(注:群主jma1不需要写入到members里面)
    
    //创建环信群组...
    String group_id = null;
    try {
     //把map对象转成json格式的String字符串 com.fasterxml.jackson.databind.ObjectMapper
     ObjectMapper json = new ObjectMapper();
     body = json.writeValueAsString(bodyMap);
     
     /**
      * 3.获取Request Headers: {“Authorization”:”Bearer ${token}”}
      */
     //********************环信创建工厂********************
     EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES)
       .getAPIFactory();
     //********************获取Request Headers: {“Authorization”:”Bearer ${token}”}********************
     authorization = factory.getContext().getAuthToken();//授权token
     System.out.println(authorization);
     
     /**
      * ********************4.发送post请求********************
      */
     String sendPost = HttpTool.sendPost(params, body, requestUrl, authorization);
     System.out.println(sendPost);
    
     //********************截取群组id******************** com.alibaba.fastjson.JSONObject
     group_id = JSONObject.parseObject(JSONObject.parseObject(sendPost).get("data").toString()).get("groupid").toString();
    
    } catch (JsonProcessingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }

 

 

<!-- ============================httpclient=发送post请求所需依赖=======================================  -->
  <!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
  <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.1</version>
  </dependency>
  <!-- ============================httpclient=发送post请求所需依赖=======================================  -->

集成环信示例代码:

1:https://github.com/easemob/emchat-server-examples

2:https://github.com/easemob/emchat-server-examples/tree/master/emchat-server-java/src/main/java/com/easemob/server/example

 

 

 

Swagger 用户界面 http://124.71.230.244:9090/plugins/restapi/v1/openapi.yaml 探索 Openfire REST API 1.11.0-SNAPSHOT OAS3 http://124.71.230.244:9090/plugins/restapi/v1/openapi.yaml 这是Openfire实时通服务器的REST API文档。 点燃实时基金会 - 网站 阿帕奇 2.0 服务器 /插件 授权 聚类 报告Openfire集群的状态 获取 /restapi/v1/聚类/节点/{nodeId} 获取特定的集群节点 获取 /restapi/v1/聚类/节点 获取所有集群节点 获取 /restapi/v1/聚类/状态 获取聚类状态 用户组 管理Openfire用户组。 获取 /restapi/v1/群组 获取群组 发布 /restapi/v1/群组 创建群组 获取 /restapi/v1/groups/{groupName} 获取群组 放置 /restapi/v1/groups/{groupName} 更新群组 删除 /restapi/v1/groups/{groupName} 删除群组 聊天室 管理多用户聊天室。 发布 /restapi/v1/chatrooms/{roomName}/{affiliation}/{jid} 添加房间隶属 删除 /restapi/v1/chatrooms/{roomName}/{affiliation}/{jid} 移除房间关联 发布 /restapi/v1/chatrooms/{roomName}/{affiliation}/group/{groupname} 添加房间隶属关系 删除 /restapi/v1/chatrooms/{roomName}/{affiliation}/group/{groupname} 移除房间关联 获取 /restapi/v1/chatrooms/{roomName}/{affiliation} 所有房间分配 放置 /restapi/v1/chatrooms/{roomName}/{affiliation} 更换房间隶属关系 发布 /restapi/v1/chatrooms/{roomName}/{affiliation} 添加房间隶属关系 获取 /restapi/v1/聊天室 获取聊天室 发布 /restapi/v1/聊天室 创建聊天室 发布 /restapi/v1/聊天室/批量 创建多个聊天室 获取 /restapi/v1/chatrooms/{roomName} 获取聊天室 放置 /restapi/v1/chatrooms/{roomName} 更新聊天室 删除 /restapi/v1/chatrooms/{roomName} Delete chat room GET /restapi/v1/chatrooms/{roomName}/chathistory Get room history GET /restapi/v1/chatrooms/{roomName}/occupants Get room occupants GET /restapi/v1/chatrooms/{roomName}/participants Get room participants POST /restapi/v1/chatrooms/{roomName}/invite/{jid} Invite user or group POST /restapi/v1/chatrooms/{roomName}/invite Invite a collection of users and/or groups Chat service Managing Multi-User chat services. GET /restapi/v1/chatservices Get chat services POST /restapi/v1/chatservices Create new multi-user chat service Message Sending (chat) messages to users. POST /restapi/v1/messages/users Broadcast Message Archive Server-sided storage of chat messages. GET /restapi/v1/archive/messages/unread/{jid} Unread message count Security Audit Log Inspecting the security audit log. GET /restapi/v1/logs/security Get log entries Client Sessions Managing live client sessions. GET /restapi/v1/sessions Get all sessions GET /restapi/v1/sessions/{username} Get user sessions DELETE /restapi/v1/sessions/{username} Kick user sessions Statistics Inspecting Openfire statistics. GET /restapi/v1/system/statistics/sessions Get client session counts System Managing Openfire system configuration GET /restapi/v1/system/properties Get system properties POST /restapi/v1/system/properties Create system property GET /restapi/v1/system/properties/{propertyKey} Get system property PUT /restapi/v1/system/properties/{propertyKey} Update system property DELETE /restapi/v1/system/properties/{propertyKey} Remove system property GET /restapi/v1/system/liveness Perform all liveness checks GET /restapi/v1/system/liveness/deadlock Perform 'deadlock' liveness check. GET /restapi/v1/system/liveness/properties Perform 'properties' liveness check. GET /restapi/v1/system/readiness Perform all readiness checks GET /restapi/v1/system/readiness/cluster Perform 'cluster' readiness check GET /restapi/v1/system/readiness/connections Perform 'connections' readiness check GET /restapi/v1/system/readiness/plugins Perform 'plugins' readiness check GET /restapi/v1/system/readiness/server Perform 'server started' readiness check Users Managing Openfire users. POST /restapi/v1/users/{username}/groups/{groupName} Add user to group DELETE /restapi/v1/users/{username}/groups/{groupName} Delete user from group GET /restapi/v1/users/{username}/groups Get user's groups POST /restapi/v1/users/{username}/groups Add user to groups DELETE /restapi/v1/users/{username}/groups Delete user from groups POST /restapi/v1/lockouts/{username} Lock user out DELETE /restapi/v1/lockouts/{username} Unlock user GET /restapi/v1/users/{username}/roster Retrieve user roster POST /restapi/v1/users/{username}/roster Create roster entry PUT /restapi/v1/users/{username}/roster/{rosterJid} Update roster entry DELETE /restapi/v1/users/{username}/roster/{rosterJid} Remove roster entry GET /restapi/v1/users Get users POST /restapi/v1/users Create user GET /restapi/v1/users/{username} Get user PUT /restapi/v1/users/{username} Update user DELETE /restapi/v1/users/{username} Delete user UserService (deprecated) Undocumented UserService endpoint, retained for backwards compatibility. GET /restapi/v1/userservice POST /restapi/v1/userservice default GET /application.wadl/{path} GET /application.wadl Schemas ClusterNodeEntity ClusterNodeEntities ClusteringEntity GroupEntity 组实体 错误响应 附属实体 MUC房间实体 房间创建结果实体 房间创建结果实体 MUC房间实体 MUC房间消息实体 MUC房间消息实体 占用者实体 占用者实体 参与者实体 参与者实体 MUC邀请实体 MUC邀请实体 MUC服务实体 MUC服务实体 消息实体 消息存档实体 安全审计日志 安全审计日志 会话实体 会话实体 会话计数 系统属性 系统属性 用户组实体 名册项实体 名册实体 用户实体 用户属性 用户实体 错误 Google 翻译 原文 提供更好的翻译建议
最新发布
10-03
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值