1.为测试Rest API发送实时消息,下载leanchat代码后修改appid及appkey为自己所建立的测试应用所属的appid及appkey
2.将修改后的leanchat安装到手机中,并注册了两个用户
3.后台使用Apache的HttpClient调用Rest API,在两用户之间建立会话,然后获取产生的会话ID
4.再使用发送消息API的地址,建立新的HttpPost对象,指定appid,appkey以及master key,按照API所规定的数据格式传递数据,执行后,后台http状态码返回200,显示成功。但是手机端未能接收到任何消息,在lean cloud的控制台实时消息统计中能够获取消息数量。
以下为实时消息部分的代码:
public static void realTimeMessage(String convUrl,String msgUrl,String from,String to,String appId,String appKey,String message){
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(convUrl);
post.setHeader("X-AVOSCloud-Application-Id", appId);
post.setHeader("X-AVOSCloud-Application-Key", appKey);
post.setHeader("Content-Type", "application/json");
String conversion = "{\"name\":\"会话\",\"m\":[\""+from+"\",\""+to+"\"],\"c\":\""+to+"\",\"attr\":{\"type\":0}}";
StringEntity se = new StringEntity(conversion, "UTF-8");
se.setContentType("application/json");
post.setEntity(se);
HttpResponse response = httpClient.execute(post);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
StringBuilder result = new StringBuilder();
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = null;
while (((line = reader.readLine()) != null)) {
result.append(line);
}
reader.close();
JSONObject jsonObject = JSONObject.parseObject(result.toString());
String convId = jsonObject.getString("objectId");
if(StringUtils.isNotBlank(convId)){
HttpPost postMsg = new HttpPost(msgUrl);
httpClient = new DefaultHttpClient();
postMsg.setHeader("X-AVOSCloud-Application-Id", appId);
postMsg.setHeader("X-AVOSCloud-Application-Key", appKey);
postMsg.setHeader("X-AVOSCloud-Master-Key", "ja4yh15bo6xuhq6gi74o0npfgf13dja7y1n7pfkzilhfz07p");
postMsg.setHeader("Content-Type", "application/json");
String msgData = "{\"from_peer\": \""+from+"\",\"message\": \""+message+"\", \"conv_id\": \""+convId+"\",\"transient\": false}";
StringEntity msg = new StringEntity(msgData, "UTF-8");
msg.setContentType("application/json");
postMsg.setEntity(msg);
HttpResponse msgResp = httpClient.execute(postMsg);
if(msgResp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
StringBuilder msgRespResult = new StringBuilder();
HttpEntity msgEntity = msgResp.getEntity();
InputStream msgInputStream = msgEntity.getContent();
InputStreamReader msgInputStreamReader = new InputStreamReader(msgInputStream);
BufferedReader msgReader = new BufferedReader(msgInputStreamReader);
String line1 = null;
while (((line1 = msgReader.readLine()) != null)) {
msgRespResult.append(line1);
}
msgReader.close();
System.out.println(msgRespResult.toString());
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
-
创建时间
15年7月25日
-
最后回复
15年8月1日
-
15
回复
-
2.4K
浏览
-
4
用户
-
2
链接