java实现即时通信的完整步骤分享
前言
移动社交是我们日常生活中很常见的软件,最近在做即时通信,我用的是环信,和大家分享一下~~
环信的API都是基于JSON的,所以在构造HTTP请求的时候,要指定请求头:
注意==》环信API必须携带token才可以访问。
创建一个认证类
publicclassAuthentic{ privatestaticTokentoken=newToken(); privateTalkHttpServiceservice; publicAuthentic(TalkHttpServiceservice){ this.service=service; } publicAuthentic(TalkHttpServiceservice,Tokentoken){ this.service=service; if(token!=null){ Authentic.token=token; } } publicTokengetToken(){ this.flush(); returntoken; } publicvoidtask(){ this.flush(); } /** *@describe申请认证POSTPUT这两种请求携带参数 *@author何章怀晓hezhanghuaixiao *@date2020/9/817:02 *@other */ publicvoidapplyAuthentication(HttpEntityEnclosingRequestBaserequest){ this.flush(); request.addHeader("Authorization","Bearer"+token.toString()); } /** *@describe申请认证GETDELETE这两种请求不携带参数 *@author何章怀晓hezhanghuaixiao *@date2020/9/817:02 *@other */ publicvoidapplyAuthentication(HttpRequestBaserequest){ this.flush(); request.addHeader("Authorization","Bearer"+token.toString()); } privatevoidflush(){ synchronized(Authentic.class){ try{ //如果超时 if(token.isExpire()){ //判断APPID和秘钥信息 if(_Global.APP_CLIENT_ID!=null&&_Global.APP_CLIENT_SECRET!=null){ Mapparam=newHashMap (); param.put("grant_type","client_credentials"); param.put("client_id",_Global.APP_CLIENT_ID); param.put("client_secret",_Global.APP_CLIENT_SECRET); //请求获取token TalkNoderes=service .request(_Global.URR_TOKEN,_Global.HTTP_METHOD_POST,param,null,null); //成功获取token if(res!=null&&res.getAccess_token()!=null&&res.getExpires_in()!=null &&res.getExpires_in()>0){ //赋值 token=newToken(res.getAccess_token(), res.getExpires_in()*1000+System.currentTimeMillis()); } } } }catch(Exceptione){ e.printStackTrace(); } } } publicstaticclassToken{ privateStringtoken; privateLongexpire; publicToken(){ } publicToken(Stringtoken,longexpire){ this.token=token; this.expire=expire; } publicStringgetToken(){ returntoken; } publicvoidsetToken(Stringtoken){ this.token=token; } publicLonggetExpire(){ returnexpire; } publicvoidsetExpire(Longexpire){ this.expire=expire; } publicbooleanisExpire(){ returnexpire==null||System.currentTimeMillis()>expire; } @Override publicStringtoString(){ returntoken; } } }
创建请求接口
publicinterfaceTalkHttpService{ /** @describe @param *@paramurl请求地址 *@parammethod 请求方法 *@paramparam 参数 *@paramauth 加密认证 *@paramfield 字段转换 @returncom.hedashi.protal.model.TalkNode @author何章怀晓hezhanghuaixiao @date2020/9/817:21 @other */ TalkNoderequest(Stringurl,intmethod,Objectparam, Authenticauth,String[][]field)throwsException; /** @describe @param *@paramurl请求地址 *@paramfile 文件名称 *@paramauth 加密认证 *@paramequal 字段转换 @returncom.hedashi.protal.model.TalkNode @author何章怀晓hezhanghuaixiao @date2020/9/817:21 @other */ TalkNodeupload(Stringurl,Filefile,Authenticauth, String[][]equal)throwsException; /** @describe @param *@paramurl请求地址 *@paramfile 文件名称 *@paramauth 加密认证 *@paramheader 请求头 @returnvoid @author何章怀晓hezhanghuaixiao @date2020/9/817:21 @other */ voiddownLoad(Stringurl,Filefile,Authenticauth, Mapheader)throwsException; }
创建全局变量对不同模块操作
/* @describe全局变量 @params @return @author何章怀晓 @date2020/7/309:30 @other */ publicclass_Global{ publicstaticStringAPP_KEY=""; publicstaticStringAPP_CLIENT_ID=""; publicstaticStringAPP_CLIENT_SECRET=""; //每页数量 publicstaticintAPP_PAGE_SIZE=10; publicstaticfinalintHTTP_METHOD_GET=1; publicstaticfinalintHTTP_METHOD_POST=2; publicstaticfinalintHTTP_METHOD_PUT=3; publicstaticfinalintHTTP_METHOD_DELETE=4; publicstaticfinalStringURL_HOST="http://a1.easemob.com/"+APP_KEY.replace("#","/")+"/"; publicstaticfinalStringURR_TOKEN=URL_HOST+"token"; publicstaticfinalStringURL_CHAT=URL_HOST+"chatmessages"; publicstaticfinalStringURL_GROUP=URL_HOST+"chatgroups"; publicstaticfinalStringURL_FILE=URL_HOST+"chatfiles"; publicstaticfinalStringURL_ROOM=URL_HOST+"chatrooms"; publicstaticfinalStringURL_MESSAGES=URL_HOST+"messages"; publicstaticfinalStringURL_USER=URL_HOST+"users"; }
请求管理类
packagecom.hedashi.protal.service.impl; importcom.hedashi.protal.model.TalkNode; importcom.hedashi.protal.model.Authentic; importcom.hedashi.protal.service.TalkHttpService; importcom.hedashi.protal.util.JsonTool; importcom.hedashi.protal.util._Global; importjava.io.File; importjava.io.FileOutputStream; importjava.io.InputStream; importjava.net.URI; importjava.util.Map; importjava.util.Map.Entry; importorg.apache.http.HttpEntity; importorg.apache.http.HttpResponse; importorg.apache.http.HttpStatus; importorg.apache.http.client.methods.HttpDelete; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.client.methods.HttpPut; importorg.apache.http.entity.StringEntity; importorg.apache.http.entity.mime.MultipartEntity; importorg.apache.http.entity.mime.content.ContentBody; importorg.apache.http.entity.mime.content.FileBody; importorg.apache.http.impl.client.CloseableHttpClient; importorg.apache.http.impl.client.HttpClients; importorg.apache.http.util.EntityUtils; importorg.springframework.stereotype.Service; @Service publicclassTalkHttpServiceImplApacheimplementsTalkHttpService{ /** @describe @param *@paramurl请求路径 *@parammethod方式 *@paramparam参数 *@paramauth认证 *@paramfield将相应结果封装到本地 @returncom.hedashi.protal.model.TalkNode @author何章怀晓hezhanghuaixiao @date2020/9/817:39 @other */ @Override publicTalkNoderequest(Stringurl,intmethod,Objectparam, Authenticauth,String[][]field)throwsException{ //获得可关闭的连接 CloseableHttpClientclient=this.getClient(); try{ HttpResponseresponse=null; //区分请求方式 switch(method){ case_Global.HTTP_METHOD_GET: //构建请求 HttpGetget=newHttpGet(url); if(auth!=null){ //如果未认证请求认证 auth.applyAuthentication(get); } //固定请求头信息为JSON get.addHeader("Content-Type","application/json"); response=client.execute(get); break; case_Global.HTTP_METHOD_POST: HttpPostpost=newHttpPost(url); if(auth!=null){ auth.applyAuthentication(post); } //POST携带参数 if(param!=null){ //参数编码放入请求体 post.setEntity(newStringEntity(JsonTool.write(param), "UTF-8")); } post.addHeader("Content-Type","application/json"); response=client.execute(post); break; case_Global.HTTP_METHOD_PUT: HttpPutput=newHttpPut(url); if(put!=null){ auth.applyAuthentication(put); } if(param!=null){ put.setEntity(newStringEntity(JsonTool.write(param), "UTF-8")); } put.addHeader("Content-Type","application/json"); response=client.execute(put); break; case_Global.HTTP_METHOD_DELETE: HttpDeletedelete=newHttpDelete(url); if(auth!=null){ auth.applyAuthentication(delete); } delete.addHeader("Content-Type","application/json"); response=client.execute(delete); break; default: thrownewException("非法请求方式"); } intcode=response.getStatusLine().getStatusCode(); //判断返回code如果为200 if(code==HttpStatus.SC_OK){ //获取响应体 HttpEntityentity=response.getEntity(); if(entity!=null){ //解析 Stringjson=EntityUtils.toString(entity,"UTF-8"); if(field!=null&&field.length>0){ for(String[]temp:field){ json=json.replace(temp[0],temp[1]); } } //解析为实体类 TalkNodetalkNode=(TalkNode)JsonTool.read(json,TalkNode.class); talkNode.setStatusCode(code); returntalkNode; } }else{ //非200将code返回 returnnewTalkNode(code); } }catch(Exceptione){ throwe; }finally{ client.close(); } returnnull; } @Override publicTalkNodeupload(Stringurl,Filefile,Authenticauth, String[][]equal)throwsException{ CloseableHttpClientclient=this.getClient(); try{ HttpPostpost=newHttpPost(); post.setURI(newURI(url)); if(auth!=null){ auth.applyAuthentication(post); } post.addHeader("restrict-access","true"); ContentBodybody=newFileBody(file); MultipartEntitypart=newMultipartEntity(); part.addPart("file",body); post.setEntity(part); HttpResponseresponse=client.execute(post); intcode=response.getStatusLine().getStatusCode(); if(code==HttpStatus.SC_OK){ HttpEntityentity=response.getEntity(); if(entity!=null){ Stringjson=EntityUtils.toString(entity,"UTF-8"); if(equal!=null&&equal.length>0){ for(String[]temp:equal){ json=json.replace(temp[0],temp[1]); } } TalkNodetalkNode=(TalkNode)JsonTool.read(json,TalkNode.class); talkNode.setStatusCode(code); returntalkNode; } } }catch(Exceptione){ throwe; }finally{ client.close(); } returnnull; } @Override publicvoiddownLoad(Stringurl,Filefile,Authenticauth, Mapheader)throwsException{ CloseableHttpClientclient=this.getClient(); try{ HttpGetget=newHttpGet(); get.setURI(newURI(url)); if(auth!=null){ auth.applyAuthentication(get); } for(Entry en:header.entrySet()){ get.addHeader(en.getKey(),en.getValue()); } HttpResponseresponse=client.execute(get); if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ HttpEntityentity=response.getEntity(); if(entity!=null){ InputStreamin=entity.getContent(); FileOutputStreamfos=newFileOutputStream(file); byte[]data=newbyte[10*1024]; intlen=0; while((len=in.read(data))!=-1){ fos.write(data,0,len); } fos.flush(); fos.close(); in.close(); } } }catch(Exceptione){ throwe; }finally{ client.close(); } } privateCloseableHttpClientgetClient(){ returnHttpClients.createDefault(); } }
创建业务请求和响应格式类
packagecom.hedashi.protal.model; importjava.util.List; importjava.util.Map; /** @describe根据不同的业务封装不同的返回结果,该格式在发送请求的时候就被指定 @author何章怀晓hezhanghuaixiao @date2020/9/817:42 @other */ publicclassTalkNode{ publicstaticfinalString[][]DATA_ENTITIES=newString[][]{{"entities","entities_share"}, {"share-secret","share_secret"}}; publicstaticfinalString[][]DATA_ARRAY=newString[][]{{"data","data_array"}}; publicstaticfinalString[][]DATA_LIST=newString[][]{{"data","data_list"}}; publicstaticfinalString[][]DATA_MAP=newString[][]{{"data","data_map"}}; publicstaticfinalString[][]DATA_CHAT_LIST=newString[][]{{"entities","data_chat_list"}}; publicstaticfinalString[][]DATA_ROOM=newString[][]{{"data","data_room"}}; publicstaticfinalString[][]DATA_ROOM_LIST=newString[][]{{"data","data_room_list"}, {"public","public_room"}}; publicstaticfinalString[][]DATA_ROOM_REDO=newString[][]{{"data","data_room_rodo"}}; publicstaticfinalString[][]DATA_ROOM_REDO_LIST=newString[][]{ {"data","data_room_redo_list"}}; publicstaticfinalString[][]DATA_GROUP=newString[][]{{"data","data_group"}}; publicstaticfinalString[][]DATA_GROUP_UPDATE=newString[][]{{"data","data_group_update"}}; publicstaticfinalString[][]DATA_GROUP_OWNER=newString[][]{{"data","data_group_owner"}}; publicstaticfinalString[][]DATA_GROUP_LIST=newString[][]{{"data","data_group_list"}}; publicstaticfinalString[][]DATA_GROUP_LIST_MEMBER=newString[][]{ {"data","data_group_list_member"}}; publicstaticfinalString[][]DATA_GROUP_LIST_NEW=newString[][]{ {"data","data_group_list_new"},{"public","public_group"}}; publicstaticfinalString[][]DATA_GROUP_FRIEND=newString[][]{{"data","data_group_friend"}}; publicstaticfinalString[][]DATA_GROUP_FRIEND_LIST=newString[][]{ {"data","data_group_friend_list"}}; privateStringaccess_token; privateStringaction; privateStringapplication; privateStringapplicationName; privateLongcount; privateStringcursor; privateIntegerduration; privateLongexpires_in; privateStringorganization; privateStringpath; privateIntegerstatusCode; privateLongtimestamp; privateStringuri; privateMapparams; privateTalkUseruser; privateList entities; privateString[]data_array; privateMap data_map; privateList
工具类
publicclassHuanXinUtil{ privatestaticTalkDataServiceservice=null; /** @describe初始化 @param *@param @returnvoid @author何章怀晓hezhanghuaixiao @date2020/9/817:26 @other */ privatestaticvoidinit(){ if(service==null){ //初始服务端Token Authentic.Tokentoken=newAuthentic(newTalkHttpServiceImplApache()).getToken(); //token和过期时间 Authentic.TokenTEST_TOKEN=newAuthentic.Token(token.getToken(),token.getExpire()); //新建一个链接服务 service=newTalkDataServiceImpl(newTalkHttpServiceImplApache()); //修改数据业务Token service.setToken(TEST_TOKEN); } } /** @describe添加管理员 @param *@paramgroupId群组id *@paramuserid管理员id @returnboolean @author何章怀晓hezhanghuaixiao @date2020/9/817:54 @other */ publicstaticbooleanaddGroupManager(StringgroupId,Stringuserid){ try{ init(); TalkNodetalkNode=service.addGroupManager(groupId,userid); if(talkNode.getStatusCode()==200){ returntrue; } }catch(Exceptione){ e.printStackTrace(); } returnfalse; } }
service调用
@Override publicTalkNodeaddGroupManager(Stringid,StringuserId)throwsException{ Mapparam=newHashMap (); param.put("newadmin",userId); returnservice.request(_Global.URL_GROUP+"/"+id+"/admin", _Global.HTTP_METHOD_POST,param,auth,TalkNode.DATA_GROUP); }
/** *@param[groupId,managerId] *@returncom.hedashi.common.api.CommonResult *@describe后台添加群组管理员 *@author何章怀晓hezhanghuaixiao *@date2020/9/814:28 *@other */ @Override publicCommonResultaddGroupManager(StringgroupId,StringmanagerId){ booleanb=HuanXinUtil.addGroupManager(groupId,managerId); if(b){ System.out.println("环信添加管理员成功=========================="); //本地添加管理员 addGroupAdmin(groupId,managerId); returnCommonResult.success("SUCCESS"); } returnCommonResult.failed("FAILED"); }
@ApiOperation(value="群组添加管理员") @RequestMapping(value="/addGroupManager",method=RequestMethod.POST) @ResponseBody publicCommonResultaddGroupManager( @RequestParam@ApiParam(value="群组环信ID",required=true)StringgroupId, @RequestParam@ApiParam(value="管理员环信id",required=true)StringmanagerId ){ returnheUGroupService.addGroupManager(groupId,managerId); }
swagger调用
swagger返回结果
控制台
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。