官方文檔: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}