官方文档:https://docs.jiguang.cn
1、利用官方API
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray;
import net.sf.json.JSONObject;
import sun.misc.BASE64Encoder;
/**
* java后台极光推送方式一:使用Http API
* 此种方式需要自定义http请求发送客户端:HttpClient
*/
@SuppressWarnings({ "deprecation", "restriction" })
public class JiguangPush {
private static final Logger log = LoggerFactory.getLogger(JiguangPush.class);
private String masterSecret = "xxxxxxxxxxxxxxxxxxxx";
private String appKey = "xxxxxxxxxxxxxxxxxxx";
private String pushUrl = "https://api.jpush.cn/v3/push";
private boolean apns_production = true;
private int time_to_live = 86400;
private static final String ALERT = "推送信息";
/**
* 极光推送
*/
public void jiguangPush(){
String alias = "123456";//声明别名
try{
String result = push(pushUrl,alias,ALERT,appKey,masterSecret,apns_production,time_to_live);
JSONObject resData = JSONObject.fromObject(result);
if(resData.containsKey("error")){
log.info("针对别名为" + alias + "的信息推送失败!");
JSONObject error = JSONObject.fromObject(resData.get("error"));
log.info("错误信息为:" + error.get("message").toString());
}
log.info("针对别名为" + alias + "的信息推送成功!");
}catch(Exception e){
log.error("针对别名为" + alias + "的信息推送失败!",e);
}
}
/**
* 组装极光推送专用json串
* @param alias
* @param alert
* @return json
*/
public static JSONObject generateJson(String alias,String alert,boolean apns_production,int time_to_live){
JSONObject json = new JSONObject();
JSONArray platform = new JSONArray();//平台
platform.add("android");
platform.add("ios");
JSONObject audience = new JSONObject();//推送目标
JSONArray alias1 = new JSONArray();
alias1.add(alias);
audience.put("alias", alias1);
JSONObject notification = new JSONObject();//通知内容
JSONObject android = new JSONObject();//android通知内容
android.put("alert", alert);
android.put("builder_id", 1);
JSONObject android_extras = new JSONObject();//android额外参数
android_extras.put("type", "infomation");
android.put("extras", android_extras);
JSONObject ios = new JSONObject();//ios通知内容
ios.put("alert", alert);
ios.put("sound", "default");
ios.put("badge", "+1");
JSONObject ios_extras = new JSONObject();//ios额外参数
ios_extras.put("type", "infomation");
ios.put("extras", ios_extras);
notification.put("android", android);
notification.put("ios", ios);
JSONObject options = new JSONObject();//设置参数
options.put("time_to_live", Integer.valueOf(time_to_live));
options.put("apns_production", apns_production);
json.put("platform", platform);
json.put("audience", audience);
json.put("notification", notification);
json.put("options", options);
return json;
}
/**
* 推送方法-调用极光API
* @param reqUrl
* @param alias
* @param alert
* @return result
*/
public static String push(String reqUrl,String alias,String alert,String appKey,String masterSecret,boolean apns_production,int time_to_live){
String base64_auth_string = encryptBASE64(appKey + ":" + masterSecret);
String authorization = "Basic " + base64_auth_string;
return sendPostRequest(reqUrl,generateJson(alias,alert,apns_production,time_to_live).toString(),"UTF-8",authorization);
}
/**
* 发送Post请求(json格式)
* @param reqURL
* @param data
* @param encodeCharset
* @param authorization
* @return result
*/
@SuppressWarnings({ "resource" })
public static String sendPostRequest(String reqURL, String data, String encodeCharset,String authorization){
HttpPost httpPost = new HttpPost(reqURL);
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
String result = "";
try {
StringEntity entity = new StringEntity(data, encodeCharset);
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpPost.setHeader("Authorization",authorization.trim());
response = client.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), encodeCharset);
} catch (Exception e) {
log.error("请求通信[" + reqURL + "]时偶遇异常,堆栈轨迹如下", e);
}finally{
client.getConnectionManager().shutdown();
}
return result;
}
/**
* BASE64加密工具
*/
public static String encryptBASE64(String str) {
byte[] key = str.getBytes();
BASE64Encoder base64Encoder = new BASE64Encoder();
String strs = base64Encoder.encodeBuffer(key);
return strs;
}
}
2、官方 下载SDK
maven 方式
将下边的依赖条件放到你项目的 maven pom.xml 文件里。
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.2.17</version>
</dependency>
jar 包方式
请到 Release页面下载相应版本的发布包。
依赖包
slf4j / log4j (Logger)
gson (Google JSON Utils)
其中 slf4j 可以与 logback, log4j, commons-logging 等日志框架一起工作,可根据你的需要配置使用。
如果使用 Maven 构建项目,则需要在你的项目 pom.xml 里增加:
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jiguang-common</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.6.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<!-- For log4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
如果不使用 Maven 构建项目,则项目 libs/ 目录下有依赖的 jar 可复制到你的项目里去。
代码:
import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
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.notification.*;
public class JpushClientUtil {
private final static String appKey = "此处为appKey";
private final static String masterSecret = "此处为masterSecret";
private static JPushClient jPushClient = new JPushClient(masterSecret,appKey);
/**
* 推送给设备标识参数的用户
* @param registrationId 设备标识
* @param notification_title 通知内容标题
* @param msg_title 消息内容标题
* @param msg_content 消息内容
* @param extrasparam 扩展字段
* @return 0推送失败,1推送成功
*/
public static int sendToRegistrationId( String registrationId,String notification_title, String msg_title, String msg_content, String extrasparam) {
int result = 0;
try {
PushPayload pushPayload= JpushClientUtil.buildPushObject_all_registrationId_alertWithTitle(registrationId,notification_title,msg_title,msg_content,extrasparam);
System.out.println(pushPayload);
PushResult pushResult=jPushClient.sendPush(pushPayload);
System.out.println(pushResult);
if(pushResult.getResponseCode()==200){
result=1;
}
} catch (APIConnectionException e) {
e.printStackTrace();
} catch (APIRequestException e) {
e.printStackTrace();
}
return result;
}
/**
* 发送给所有安卓用户
* @param notification_title 通知内容标题
* @param msg_title 消息内容标题
* @param msg_content 消息内容
* @param extrasparam 扩展字段
* @return 0推送失败,1推送成功
*/
public static int sendToAllAndroid( String notification_title, String msg_title, String msg_content, String extrasparam) {
int result = 0;
try {
PushPayload pushPayload= JpushClientUtil.buildPushObject_android_all_alertWithTitle(notification_title,msg_title,msg_content,extrasparam);
System.out.println(pushPayload);
PushResult pushResult=jPushClient.sendPush(pushPayload);
System.out.println(pushResult);
if(pushResult.getResponseCode()==200){
result=1;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 发送给所有IOS用户
* @param notification_title 通知内容标题
* @param msg_title 消息内容标题
* @param msg_content 消息内容
* @param extrasparam 扩展字段
* @return 0推送失败,1推送成功
*/
public static int sendToAllIos(String notification_title, String msg_title, String msg_content, String extrasparam) {
int result = 0;
try {
PushPayload pushPayload= JpushClientUtil.buildPushObject_ios_all_alertWithTitle(notification_title,msg_title,msg_content,extrasparam);
System.out.println(pushPayload);
PushResult pushResult=jPushClient.sendPush(pushPayload);
System.out.println(pushResult);
if(pushResult.getResponseCode()==200){
result=1;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 发送给所有用户
* @param notification_title 通知内容标题
* @param msg_title 消息内容标题
* @param msg_content 消息内容
* @param extrasparam 扩展字段
* @return 0推送失败,1推送成功
*/
public static int sendToAll( String notification_title, String msg_title, String msg_content, String extrasparam) {
int result = 0;
try {
PushPayload pushPayload= JpushClientUtil.buildPushObject_android_and_ios(notification_title,msg_title,msg_content,extrasparam);
System.out.println(pushPayload);
PushResult pushResult=jPushClient.sendPush(pushPayload);
System.out.println(pushResult);
if(pushResult.getResponseCode()==200){
result=1;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static PushPayload buildPushObject_android_and_ios(String notification_title, String msg_title, String msg_content, String extrasparam) {
return PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
.setAudience(Audience.all())
.setNotification(Notification.newBuilder()
.setAlert(notification_title)
.addPlatformNotification(AndroidNotification.newBuilder()
.setAlert(notification_title)
.setTitle(notification_title)
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
.addExtra("androidNotification extras key",extrasparam)
.build()
)
.addPlatformNotification(IosNotification.newBuilder()
//传一个IosAlert对象,指定apns title、title、subtitle等
.setAlert(notification_title)
//直接传alert
//此项是指定此推送的badge自动加1
.incrBadge(1)
//此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,
// 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音
.setSound("sound.caf")
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
.addExtra("iosNotification extras key",extrasparam)
//此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
// .setContentAvailable(true)
.build()
)
.build()
)
//Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
// sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
// [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
.setMessage(Message.newBuilder()
.setMsgContent(msg_content)
.setTitle(msg_title)
.addExtra("message extras key",extrasparam)
.build())
.setOptions(Options.newBuilder()
//此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
.setApnsProduction(false)
//此字段是给开发者自己给推送编号,方便推送者分辨推送记录
.setSendno(1)
//此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
.setTimeToLive(86400)
.build()
)
.build();
}
private static PushPayload buildPushObject_all_registrationId_alertWithTitle(String registrationId,String notification_title, String msg_title, String msg_content, String extrasparam) {
System.out.println("----------buildPushObject_all_all_alert");
//创建一个IosAlert对象,可指定APNs的alert、title等字段
//IosAlert iosAlert = IosAlert.newBuilder().setTitleAndBody("title", "alert body").build();
return PushPayload.newBuilder()
//指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
.setPlatform(Platform.all())
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
.setAudience(Audience.registrationId(registrationId))
//jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
.setNotification(Notification.newBuilder()
//指定当前推送的android通知
.addPlatformNotification(AndroidNotification.newBuilder()
.setAlert(notification_title)
.setTitle(notification_title)
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
.addExtra("androidNotification extras key",extrasparam)
.build())
//指定当前推送的iOS通知
.addPlatformNotification(IosNotification.newBuilder()
//传一个IosAlert对象,指定apns title、title、subtitle等
.setAlert(notification_title)
//直接传alert
//此项是指定此推送的badge自动加1
.incrBadge(1)
//此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,
// 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音
.setSound("sound.caf")
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
.addExtra("iosNotification extras key",extrasparam)
//此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
//取消此注释,消息推送时ios将无法在锁屏情况接收
// .setContentAvailable(true)
.build())
.build())
//Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
// sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
// [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
.setMessage(Message.newBuilder()
.setMsgContent(msg_content)
.setTitle(msg_title)
.addExtra("message extras key",extrasparam)
.build())
.setOptions(Options.newBuilder()
//此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
.setApnsProduction(false)
//此字段是给开发者自己给推送编号,方便推送者分辨推送记录
.setSendno(1)
//此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天;
.setTimeToLive(86400)
.build())
.build();
}
private static PushPayload buildPushObject_android_all_alertWithTitle(String notification_title, String msg_title, String msg_content, String extrasparam) {
System.out.println("----------buildPushObject_android_registrationId_alertWithTitle");
return PushPayload.newBuilder()
//指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
.setPlatform(Platform.android())
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
.setAudience(Audience.all())
//jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
.setNotification(Notification.newBuilder()
//指定当前推送的android通知
.addPlatformNotification(AndroidNotification.newBuilder()
.setAlert(notification_title)
.setTitle(notification_title)
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
.addExtra("androidNotification extras key",extrasparam)
.build())
.build()
)
//Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
// sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
// [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
.setMessage(Message.newBuilder()
.setMsgContent(msg_content)
.setTitle(msg_title)
.addExtra("message extras key",extrasparam)
.build())
.setOptions(Options.newBuilder()
//此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
.setApnsProduction(false)
//此字段是给开发者自己给推送编号,方便推送者分辨推送记录
.setSendno(1)
//此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
.setTimeToLive(86400)
.build())
.build();
}
private static PushPayload buildPushObject_ios_all_alertWithTitle( String notification_title, String msg_title, String msg_content, String extrasparam) {
System.out.println("----------buildPushObject_ios_registrationId_alertWithTitle");
return PushPayload.newBuilder()
//指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
.setPlatform(Platform.ios())
//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
.setAudience(Audience.all())
//jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
.setNotification(Notification.newBuilder()
//指定当前推送的android通知
.addPlatformNotification(IosNotification.newBuilder()
//传一个IosAlert对象,指定apns title、title、subtitle等
.setAlert(notification_title)
//直接传alert
//此项是指定此推送的badge自动加1
.incrBadge(1)
//此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,
// 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音
.setSound("sound.caf")
//此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
.addExtra("iosNotification extras key",extrasparam)
//此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
// .setContentAvailable(true)
.build())
.build()
)
//Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
// sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
// [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
.setMessage(Message.newBuilder()
.setMsgContent(msg_content)
.setTitle(msg_title)
.addExtra("message extras key",extrasparam)
.build())
.setOptions(Options.newBuilder()
//此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
.setApnsProduction(false)
//此字段是给开发者自己给推送编号,方便推送者分辨推送记录
.setSendno(1)
//此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
.setTimeToLive(86400)
.build())
.build();
}
// public static void main(String[] args){
// if(JpushClientUtil.sendToAllIos("testIos","testIos","this is a ios Dev test","")==1){
// System.out.println("success");
// }
// }
}
1. 设置推送平台
setPlatform(Platform.all()) //设置所有平台
setPlatform(Platform.android())//设置android
setPlatform(Platform.android_ios())//设置Android和iOS
setPlatform(Platform.ios())//设置iOS
2. 设置受众(收到推送消息的人群)
setAudience(Audience.all())设置所有受众
setAudience(Audience.tag("tag1","tag2"))//设置tag为tag1,tag2的受众,群发
setAudience(AudienceTarget.alias("alias1", "alias2")) //设置别名alias为alias1,alias2的受众,单发
注1: 更多的发送方式,可以到官网上去找文档,可以这是多个条件混合发送。由于本项目中没有那么复杂的应用需求,所以此处省略不提。
3. 设置通知方式
setNotification(Notification.alert(ALERT)) //设置通用通知,以alert方式提醒
setNotification(Notification.android(ALERT, TITLE, null))//增加标题
setNotification(Notification.newBuilder()
.addPlatformNotification(IosNotification.newBuilder()
.setAlert(ALERT)
.setBadge(5)
.setSound("happy")
.addExtra("from", "JPush")
.build())
.build())//不管什么东西,iOS的总要复杂一些。
注1: 可以不设置通知方式,让其使用默认的通知方式进行消息推送
4. 设置通知内容
setMessage(Message.content(MSG_CONTENT))//MSG_CONTENT中就是通知内容。
5. 设置控制选项
setOptions(M\options(sendno, time_to_live, override_msg_id, apns_production,big_push_duration))
当前包含如下几个可选项:
sendno int 可选 推送序号 纯粹用来作为 API 调用标识,API 返回时被原样返回,以方便 API 调用方匹配请求与返回。
time_to_live int 可选 离线消息保留时长 推送当前用户不在线时,为该用户保留多长时间的离线消息,以便其上线时再次推送。默认86400 (1 天),最长 10 天。设置为 0 表示不保留离线消息,只有推送当前在线的用户可以收到。
override_msg_id long 可选 要覆盖的消息ID 如果当前的推送要覆盖之前的一条推送,这里填写前一条推送的 msg_id 就会产生覆盖效果,即:1)该 msg_id 离线收到的消息是覆盖后的内容;2)即使该 msg_id Android 端用户已经收到,如果通知栏还未清除,则新的消息内容会覆盖之前这条通知;覆盖功能起作用的时限是:1 天。 如果在覆盖指定时限内该 msg_id 不存在,则返回 1003 错误,提示不是一次有效的消息覆盖操作,当前的消息不会被推送。
apns_production boolean 可选 APNs是否生产环境 True 表示推送生产环境,False 表示要推送开发环境; 如果不指定则为推送生产环境。
注:JPush 官方 API LIbrary (SDK) 默认设置为推送 “开发环境”。
big_push_duration int 可选 定速推送时长(分钟) 又名缓慢推送,把原本尽可能快的推送速度,降低下来,在给定的 n 分钟内,均匀地向这次推送的目标用户推送。最大值为 1440。未设置则不是定速推送。
6. 开始推送
sendPush(PushPayload类型参数)
7. 获取返回结果
PushResult类型参数,可以回去到返回值。结果大致格式如下:
{"msg_id":3270259240,"sendno":34919015}