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
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();
}
集成环信示例代码:
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