Java 极光推送
1.首先注册登录极光账号,创建应用就会自动生成AppKey 和 Master Secret
2.引入极光jar
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.3.11</version>
</dependency>
3.一种是使用极光推送官方提供的推送请求API (如需其他,按照极光文档修改即可)
import cn.jiguang.common.resp.BaseResult;
import cn.jpush.api.JPushClient;
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.Notification;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
/**
*
* @description: app推送消息
* @author: JDL
* @time: 2020/8/4 10:18
*/
public class JpushHelper {
private JPushClient jpushClient;
public final static String MASTERSECRET= "你的MASTERSECRET";
public final static String APPKEY= "你的APPKEY";
public final static String TIMEFORMAT = "yyyy-MM-dd HH:mm:ss";
private Logger logger = LoggerFactory.getLogger(JpushHelper.class);
public JpushHelper() {
jpushClient = new JPushClient(MASTERSECRET, APPKEY);
}
/**
* 指定单人、多人推送消息
*
* @param alertMsg 消息内容
* @param aliasName 推送别名
* @return 消息发送结果
*/
public BaseResult sendMsg(String alertMsg, String[] aliasName) throws Exception {
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.alias(aliasName))
.setNotification(Notification.alert(alertMsg))
.build();
BaseResult baseResult = jpushClient.sendPush(payload);
jpushClient.close();
return baseResult;
}
/**
* 对所有人发送消息
* @param alertMsg 消息内容
* @return
* @throws Exception
*/
public BaseResult sendMsg(String alertMsg) throws Exception {
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.all())//这个可以指定对android、ios发送
.setAudience(Audience.all())
.setNotification(Notification.alert(alertMsg))
.build();
BaseResult baseResult = jpushClient.sendPush(payload);
jpushClient.close();
return baseResult;
}
/**
* 发送单个定时消息
*
* @param alertMsg 消息内容
* @param time 发送时间格式:yyyyMMddHHmmss
* @param aliasName 推送别名
* @return 发送结果
*/
public BaseResult sendMsg(String alertMsg, String time, String aliasName) {
try {
String md5Hex = DigestUtils.md5Hex(aliasName);
String name = UUID.randomUUID().toString().replaceAll("-", "");
//"2017-03-28 17:50:00"
time = DateHelper.dateFmt(time, "yyyyMMddHHmmss", TIMEFORMAT);
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.alias(md5Hex))
.setNotification(Notification.alert(alertMsg))
.build();
BaseResult baseResult = jpushClient.createSingleSchedule(name, time, payload);
jpushClient.close();
return baseResult;
} catch (Exception e) {
logger.error("JpushHelper", "sendMsg", e.getMessage());
}
return null;
}
/**
* 对多人批量定时发送相同信息
*
* @param alertMsg 消息内容
* @param time 时间
* @param aliasName 推送别名
* @return 发送信息结果
*/
public BaseResult sendMsg(String alertMsg, String time, String... aliasName) {
try {
String[] md5Hex = new String[aliasName.length];
for (int i = 0; i < aliasName.length; i++) {
md5Hex[i] = DigestUtils.md5Hex(aliasName[i]);
}
time = DateHelper.dateFmt(time, "yyyyMMddHHmmss", TIMEFORMAT);
String name = UUID.randomUUID().toString().replaceAll("-", "");
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.alias(md5Hex))
.setNotification(Notification.alert(alertMsg))
.build();
BaseResult baseResult = jpushClient.createSingleSchedule(name, time, payload);
jpushClient.close();
return baseResult;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
4.另一种使用官方提供的第三方Java SDK
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
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 sun.misc.BASE64Encoder;
/**
* @Descriptions
* @Author:JDL
* @Time:2020/8/31 13:18
*/
public class JpushSend{
private static final Logger log = LoggerFactory.getLogger(JpushSend.class);
private boolean apns_production = true;
/**
* 极光推送
* alias:别名
* alert_Msg:推送消息
*/
public boolean jiguangPush(String alert_Msg,String[] alias) {
String masterSecret = "";
String appKey = "";
String pushUrl = "https://api.jpush.cn/v3/push";
int time_to_live = 86400;
try {
String result = push(pushUrl, alias, alert_Msg, appKey, masterSecret, apns_production, time_to_live);
JSONObject resData = JSONObject.fromObject(result);
if (resData.containsKey("error")) {
log.info("--------------信息推送失败!");
JSONObject error = JSONObject.fromObject(resData.get("error"));
log.info("错误信息为:" + error.get("message").toString());
return false;
}else{
log.info("--------------的信息推送成功!");
return true;
}
} catch (Exception e) {
log.error("--------------的信息推送失败!", e);
}
return false;
}
/**
* 组装极光推送专用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();
for(int i=0;i<alias.length;i++){
alias1.add(alias[i]);
}
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);
System.out.println("AAAA"+result);
} 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;
}
}
5.转载注明https://blog.csdn.net/jia814583973/article/details/107788136