1、pom文件引入相关jar包

 <!--极光推送消息start-->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency> <dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.3.</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions> </dependency> <dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jiguang-common</artifactId>
<version>1.1.</version>
</dependency> <dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1..Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency> <!--极光推送消息end-->

2、提供相关包装好的类

(1)消息封装类

package com.test.entity.common;

import com.google.gson.JsonObject;

import java.util.List;
import java.util.Map; /**
* 极光推送消息类
*/
public class JPushDeviceBean {
private String token;
private String alias_value;//别名值
private String registration_id;
private List<String> username;//所有用户别名
private String title;//标题
private String fsmessagecontent;//内容
private Integer count;//角标数
private Map<String, String> extrasMap;
private JsonObject extra; public JsonObject getExtra() {
return extra;
} public void setExtra(JsonObject extra) {
this.extra = extra;
} public Map<String, String> getExtrasMap() {
return extrasMap;
} public void setExtrasMap(Map<String, String> extrasMap) {
this.extrasMap = extrasMap;
} public String getToken() {
return token;
} public void setToken(String token) {
this.token = token;
} public String getAlias_value() {
return alias_value;
} public void setAlias_value(String alias_value) {
this.alias_value = alias_value;
} public String getRegistration_id() {
return registration_id;
} public void setRegistration_id(String registration_id) {
this.registration_id = registration_id;
} public List<String> getUsername() {
return username;
} public void setUsername(List<String> username) {
this.username = username;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public String getFsmessagecontent() {
return fsmessagecontent;
} public void setFsmessagecontent(String fsmessagecontent) {
this.fsmessagecontent = fsmessagecontent;
} public Integer getCount() {
return count;
} public void setCount(Integer count) {
this.count = count;
}
}

(2)工具类

package com.test.util;

import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.util.Map; public class JPushDevice { protected static final Logger LOG =LoggerFactory.getLogger(JPushDevice.class); private static final String URL="https://device.jpush.cn";//极光访问URL
public static long timeToLive=***;//10天 //privatestaticJPushClientjpushClient= newJPushClient(masterSecret,appKey,null,ClientConfig.getInstance()); //  //对于推送,您所需要做的就是构建PushPayload对象。
//  PushPayloadpayload=buildPushObject_ios_audienceMore_messageWithExtras();
//  PushResultresult=jpushClient.sendPush(payload); public static PushPayload buildPushObject_android_tag_alertWithTitle(String username){
return PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.alias(username))
.setNotification(Notification.alert("ALERT"))
.build();
}
//弹框
public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras(String username){
return PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.alias(username))
.setMessage(Message.newBuilder()
.setMsgContent("您有一条回复内容。。")
.addExtra("from","JPush")
.build())
.build();
}
//推送全部平台(一个用户)(无角标)
public static PushPayload oneName(String username, String title, String fsmessagecontent,
Map<String, String> extrasMap, JsonObject extra){
return PushPayload.newBuilder()
.setPlatform(Platform.all())//推送全部平台
.setAudience(Audience.newBuilder()//推送目标:别名、标签、注册ID、分群、广播等。
.addAudienceTarget(AudienceTarget.alias(username))
.build())
.setMessage(Message.newBuilder()
.setMsgContent(fsmessagecontent)//消息内容
// .setTitle(count.toString())//当做安卓的角标数
.addExtra("from","JPush")//应用内消息通道
.build())
.setNotification(Notification.newBuilder()//notification:通知内容体。是被推送到客户端的内容
.addPlatformNotification(IosNotification.newBuilder()//iOS
.setAlert(title)//弹框显示标题
// .setBadge(count)//角标
.build())
.addPlatformNotification(AndroidNotification.newBuilder()//安卓
.setAlert(fsmessagecontent)//弹框显示内容
.setTitle(title)//弹框显示标题
.addExtras(extrasMap)
.addExtra("extra",extra)
.build())
.build())
.build();
}
//推送全部平台(传多个别名用户)(有角标)
public static PushPayload AllName(String[] username,String title,String fsmessagecontent,Integer count){
return PushPayload.newBuilder()
.setPlatform(Platform.all())//推送全部平台
.setAudience(Audience.newBuilder()//推送目标:别名、标签、注册ID、分群、广播等。
.addAudienceTarget(AudienceTarget.alias(username))//别名可以是数组为并集,一次只能存1000个
.build())
.setMessage(Message.newBuilder()
.setMsgContent(fsmessagecontent)//消息内容
.setTitle(count.toString())//当做安卓的角标数
.addExtra("from","JPush")//应用内消息通道
.build())
.setNotification(Notification.newBuilder()//notification:通知
.addPlatformNotification(IosNotification.newBuilder()//iOS
.setAlert(title)//弹框显示标题
.setBadge(count)//角标
.build())
.addPlatformNotification(AndroidNotification.newBuilder()//安卓
.setAlert(fsmessagecontent)//弹框显示内容
.setTitle(title)//弹框显示标题
.build())
.build())
.build();
}
}

(3)实现类

package com.test.controller.common;

import static com.yjl.util.UploadUtil.getErrorMsg;
import static com.yjl.util.UploadUtil.getYjlResponseModel;
import static com.yjl.util.UploadUtil.isSuccess;
import static com.yjl.util.UploadUtil.setErrorMsg;
import static com.yjl.util.UploadUtil.setSuccess;
import static com.yjl.util.UploadUtil.setYjlResponseModel; import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import com.google.gson.Gson;
import com.yjl.entity.common.JPushDeviceBean;
import com.yjl.entity.common.YJLResponseModel;
import com.yjl.util.HttpClientUtil;
import com.yjl.util.JPushDevice;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
@RequestMapping("/JPushDevice")
public class JPushDeviceController{ private static Logger logger = LoggerFactory.getLogger(JPushDeviceController.class); //极光访问URL
private static final String URL = "https://device.jpush.cn";
//极光用户名
private static final String APPKEY ="极光平台生成的app的appkey";
//极光密码
private static final String MASTERSECRET ="极光平台生成的app的mastersecret"; //1.推送一个人
@RequestMapping(value = "getOneJPushDevice", method = RequestMethod.POST)
@ResponseBody
public PushResult getOneJPushDevice(@RequestBody JPushDeviceBean j) {
String aliases = getAliases(j.getAlias_value());
//一个别名
PushResult pResult = new PushResult();
//别名;
if(StringUtils.isNotBlank(aliases)){
//极光推送
JPushClient jpushClient = new JPushClient(MASTERSECRET,APPKEY,null,ClientConfig.getInstance());
PushPayload payload = JPushDevice.oneName(aliases, j.getTitle(), j.getFsmessagecontent(),j.getExtrasMap(),j.getExtra());
try {
pResult = jpushClient.sendPush(payload);
System.out.println("Got result 推送一个人 - 3" + pResult );
Thread.sleep();
// 请求结束后,调用 NettyHttpClient 中的 close 方法,否则进程不会退出。
jpushClient.close();
}
catch (APIConnectionException e) {
e.printStackTrace();
}
catch (APIRequestException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
return pResult;
}
//2.推送多人//先循环判断别名
@RequestMapping(value = "getAllJPushDevice", method = RequestMethod.POST)
@ResponseBody
public YJLResponseModel getAllJPushDevice(@RequestBody JPushDeviceBean j) {
setYjlResponseModel(new YJLResponseModel());
setErrorMsg("");
setSuccess(false);
List<String> ulist = j.getUsername();
//判断过得别名数组
if(null!=ulist && !ulist.isEmpty()){
String[] username = ulist.toArray(new String[ulist.size()]);
//转化为数组
//极光推送
JPushClient jpushClient = new JPushClient(MASTERSECRET,APPKEY,null, ClientConfig.getInstance());
PushPayload payload = JPushDevice.AllName(username, j.getTitle(), j.getFsmessagecontent(), j.getCount());
//用户别名数组1000个一次,标题,内容,角标数
PushResult pResult;
try {
pResult = jpushClient.sendPush(payload);
setSuccess(true);
System.out.println("Got result - " + new Gson().toJson(pResult) );
try {
Thread.sleep();
}
catch (InterruptedException e) {
e.printStackTrace();
}
// 请求结束后,调用 NettyHttpClient 中的 close 方法,否则进程不会退出。
jpushClient.close();
}
catch (APIConnectionException e) {
e.printStackTrace();
}
catch (APIRequestException e) {
e.printStackTrace();
}
finally {
getYjlResponseModel().setErrorMsg(getErrorMsg());
getYjlResponseModel().setSuccess(isSuccess());
}
}
return getYjlResponseModel();
}
//查询别名是否存在
public static String getAliases(String aliases){
String alia ="";
JPushDeviceBean j = new JPushDeviceBean();
j.setAlias_value(aliases);
YJLResponseModel map = getJPushDeviceAliases(j);
//查询是否含有别名
Map<String, Object> ma = (Map<String, Object>)map.getData();
if(ma.containsKey("registration_ids")){
List<String> list = (List<String>)ma.get("registration_ids");
//查询registration_ids的值不为空则含有该别名
if(null!=list && !list.isEmpty()){
System.out.println("查询别名----"+new Gson().toJson(list));
//在此内可调用极光的推送方法
alia = aliases;
//如果存在就给返回该别名
}
}
return alia;
}
//--------------------查询别名的方法-------------------------------------------
//查询别名(找不到统计项就是 null,否则为统计项的值。)
@RequestMapping(value = "getJPushDeviceAliases", method = RequestMethod.POST)
@ResponseBody
public static YJLResponseModel getJPushDeviceAliases(@RequestBody JPushDeviceBean ht) {
setYjlResponseModel(new YJLResponseModel());
setErrorMsg("");
setSuccess(false);
JSONObject response = null;
try {
StringBuilder url = new StringBuilder(URL).append("/v3/aliases/"+ht.getAlias_value());
String authorValue = getBase64();
Map<String, String> para = new HashMap<>();
response = HttpClientUtil.doGet(url.toString(), authorValue, para);
if (StringUtils.isNotEmpty((String)response.get("error"))) {
logger.info("getAliases:url+params----" + url + para);
throw new Exception();
}
setSuccess(true);
}
catch (Exception e) {
e.printStackTrace();
logger.error("getAliases:url+params----" + e);
}finally {
getYjlResponseModel().setErrorMsg(getErrorMsg());
getYjlResponseModel().setSuccess(isSuccess());
getYjlResponseModel().setData(response);
}
return getYjlResponseModel();
} //String转base64
public static String getBase64(){
Base64 base64 = new Base64();
String base64Sign ="";
String string = APPKEY+":"+MASTERSECRET;
try {
base64Sign = base64.encodeToString(string.getBytes("UTF-8"));
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return " Basic "+base64Sign;
} //测试一下
public static void main(String[] args) {
JPushDeviceController JPushDeviceController = new JPushDeviceController();
JPushDeviceBean jd = new JPushDeviceBean();
jd.setAlias_value("");//此处为待推送的用户id
jd.setTitle("推送消息");
jd.setFsmessagecontent("测试一下服务器端");
PushResult pushResult = JPushDeviceController.getOneJPushDevice(jd);
System.out.println(pushResult); }
}

3.测试一下

 //测试一下
public static void main(String[] args) {
JPushDeviceController JPushDeviceController = new JPushDeviceController();
JPushDeviceBean jd = new JPushDeviceBean();
jd.setAlias_value("");
jd.setTitle("推送消息");
jd.setFsmessagecontent("测试一下服务器端");
Map<String,String> extrasParam = new HashMap<>();
extrasParam.put("额外参数1","额外参数内容1");
jd.setExtrasMap(extrasParam);
PushResult pushResult = JPushDeviceController.getOneJPushDevice(jd);
System.out.println(pushResult); }

极光推送消息——Alias别称方式(Andirod)的更多相关文章

  1. 极光推送-Java后台实现方式一:Http API

    Java后台实现极光推送有两种方式,一种是使用极光推送官方提供的推送请求API:https://api.jpush.cn/v3/push,另一种则是使用官方提供的第三方Java APIjar包,这里先 ...

  2. Yii1.1框架实现PHP极光推送消息通知

    一.下载极光推送PHP SDK,解压后放在/protected/components/目录下,如下图所示: 二.完善修改下官方的demo例子,我这里复制一份demo,改为NotifyPush.php, ...

  3. ios之极光推送消息收到以后对消息的处理总结

    当我们的APP收到推送消息后,通常需要根据推送内容点击消息进入到指定的页面 这里讲一下收到推送消息后的处理,分为三种情况 :1.APP处于前台运行情况下     2.APP处于后台挂起情况下   3. ...

  4. 极光推送消息——RegistrationID方式

    1.工具类 package com.test.util; import cn.jiguang.common.resp.APIConnectionException; import cn.jiguang ...

  5. ios -- 极光推送《2》--极光推送消息推送成功,但是手机收不到的解决方法

    1.确认证书是否与app的Bundle ID是否一致 2. 确认你的推送证书是否已经过期 3.确认你的APP_KEY是否和极光APP_KEY是否一致 4.正确调用bindChannel,并成功返回ap ...

  6. JPush 极光推送 消息推送 实例

    简介 官网:https://www.jpush.cn/ 极光推送(JPush)是一个端到端的推送服务,使得服务器端消息能够及时地推送到终端用户手机上,让开发者积极地保持与用户的连接,从而提高用户活跃度 ...

  7. Python3使用钉钉机器人推送消息(签名方式)

    import time import hmac import hashlib import base64 import urllib import json import requests impor ...

  8. 极光推送经验之谈-Java后台服务器实现极光推送的两种实现方式

    原创作品,可以转载,但是请标注出处地址http://www.cnblogs.com/V1haoge/p/6439313.html Java后台实现极光推送有两种方式,一种是使用极光推送官方提供的推送请 ...

  9. 极光推送_总结_01_Java实现极光推送

    一.代码实现 1.配置类—Env.java package com.ray.jpush.config; /**@desc : 极光推送接入配置 * * @author: shirayner * @da ...

随机推荐

  1. 使用wait/notify/notifyAll实现线程间通信的几点重要说明

    在Java中,可以通过配合调用Object对象的wait()方法和notify()方法或notifyAll()方法来实现线程间的通信.在线程中调用wait()方法,将阻塞等待其他线程的通知(其他线程调 ...

  2. [Mysql] GroupBy 分组,按天、周、月

    简单说明: 最近在做报表功能的时候,需要将数据按天.周和月进行合并展示(数据记录都是按天20190701). 正文: 说明:数据表中date都是int类型:如 20190701 一.按天 SELECT ...

  3. 如何使用有道云笔记的Markdown----初级版?

    我一般整理笔记用的是用有道云笔记,在这里,Markdown怎么用? 什么是Markdown?Markdown是一种轻量级的「标记语言」,通常为程序员群体所用,目前它已是全球最大的技术分享网站 GitH ...

  4. Zookeeper之Leader选举过程

    Leader在集群中是一个非常重要的角色,负责了整个事务的处理和调度,保证分布式数据一致性的关键所在.既然Leader在ZooKeeper集群中这么重要所以一定要保证集群在任何时候都有且仅有一个Lea ...

  5. [系列] - go-gin-api 路由中间件 - 日志记录(三)

    目录 概述 gin.Logger() 自定义 Logger() 源码地址 go-gin-api 系列文章 概述 首先同步下项目概况: 上篇文章分享了,规划项目目录和参数验证,其中参数验证使用的是 va ...

  6. redis 原理系列之--字符串存储的实现原理(1)

    背景 redis功能强大,几乎已经成了现代大中型服务必备的缓存技术了. 除了十分给力的缓存功能,redis当做消息队列,数据库也有着不错的表现. 我们都知道,redis 有五种数据类型,string, ...

  7. bzoj 2002 弹飞绵羊 lct裸题

    上一次用分块过了, 今天换了一种lct(link-cut tree)的写法. 学lct之前要先学过splay. lct 简单的来说就是 一颗树, 然后每次起作用的都是其中的某一条链. 所以每次如果需要 ...

  8. Python 之父的解析器系列之六:给 PEG 语法添加动作

    原题 | Adding Actions to a PEG Grammar 作者 | Guido van Rossum(Python之父) 译者 | 豌豆花下猫("Python猫"公 ...

  9. [1]尝试用Unity3d制作一个王者荣耀(持续更新)->AssetBundle管理器

    如果已经看过本章节:目录传送门:这是目录鸭~ 1.AssetBundleManager: 首先我们创建一个文件夹,叫AssetBundleManager,再创建Csharp(即C#)脚本,名为Asse ...

  10. android 之图片异步加载

    一.概述 本文来自"慕课网" 的学习,只是对代码做一下分析 图片异步加载有2种方式:  (多线程/线程池) 或者 用其实AsyncTask , 其实AsyncTask底层也是用的多 ...