Java 极光推送

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

极光推送是一款用于实现消息推送的云服务平台,它提供了丰富的消息推送功能。在Java后台中整合极光推送可以通过以下几个步骤来实现: 1. 注册极光推送账号并创建应用:首先,你需要在极光推送官网注册账号,并创建一个应用。在创建应用的过程中,会生成一个AppKey和一个Master Secret,这对应用进行身份验证非常重要。 2. 导入极光推送SDK:在你的Java项目中,你需要导入极光推送Java SDK。你可以在极光推送官网上下载SDK,并将其添加到你的项目中。 3. 配置AppKey和Master Secret:在你的项目中找到配置文件(比如.properties文件),将AppKey和Master Secret配置到文件中。这些配置信息将用于与极光推送服务器进行身份验证。 4. 初始化JPushClient对象:在你的代码中,通过使用AppKey和Master Secret初始化一个JPushClient对象。这个对象将用于与极光推送服务器进行通信。 5. 构建推送消息:使用JPushClient对象,你可以构建不同类型的推送消息,比如通知、自定义消息等。根据你的需求,设置相应的参数,比如目标平台、接收者、通知内容等。 6. 发送推送消息:调用JPushClient对象的sendPush方法,将构建好的推送消息发送给极光推送服务器。服务器会根据你的设置,将消息推送给相应的设备。 以上就是极光推送Java后台整合的基本步骤。你可以根据自己的需求,进一步深入学习和使用极光推送的其他功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值