极光推送操作示例

极光推送操作示例

官网:https://www.jiguang.cn/

使用感想:华为、小米、苹果、魅族、vivo、open等存在自己的推送,其他的机型走极光

一、简介

 极光推送(JPush)是独立的第三方云推送平台,致力于为全球移动应用开发者提供移动消息推送服务。

二、使用

 1、pom依赖

        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.54</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.8</version>
        </dependency>

 2、参数获取

  a、登录极光官网->创建应用->应用设置

  b、获取masterSecret、 appKey   

 3、工具类代码

package cn.wildfirechat.push.android.jpush;

import cn.wildfirechat.push.PushMessage;
import com.alibaba.fastjson.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 org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

/**
 * 极光推送
 *
 * @author :fuanfei
 * @date :2020/5/18
 */
@Component
public class JPush {
    private static final Logger log = LoggerFactory.getLogger(JPush.class);
    private static String masterSecret = "";
    private static String appKey = "";
    private static String pushUrl = "https://api.jpush.cn/v3/push";
    private static boolean apns_production = true;
    private static int time_to_live = 86400;
    private static final String ALERT = "极光推送信息测试一波";
    private static final String TITLE = "【您有一条消息...】";

  /*  public static void main(String[] args) {
        push();
    }*/
    /**
     * 极光推送
     */
    public void push(PushMessage pushMessage) {
        String title=pushMessage.getSenderName();
        String alert=pushMessage.pushContent;
        String alias = "wl02";//声明别名
        try {
            String result = push(pushUrl, alias,title, 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());
            }else {
                log.info("针对别名为" + alias + "的信息推送成功!");
            }
        } catch(Exception e) {
            log.error("针对别名为" + alias + "的信息推送失败!", e);
        }
    }

    /**
     * 组装极光推送专用json串
     *
     * @param alias
     * @param alert
     * @return json
     */
    public static JSONObject generateJson(String alias,String title, 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("title", title);
        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 title, 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;
        //log.info("-------------"+authorization);
        return sendPostRequest(reqUrl, generateJson(alias,title, 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;
    }
}

 4、例子使用

  极光官网下载手机对应的JPush SDK Demo ->高级功能->设置alias、tag进行推送

 

======================================官方推荐代码

1、pom依赖

<dependency>
    <groupId>cn.jpush.api</groupId>
    <artifactId>jpush-client</artifactId>
    <version>3.4.7</version>
</dependency>
<dependency>
    <groupId>cn.jpush.api</groupId>
    <artifactId>jiguang-common</artifactId>
    <version>1.1.8</version>
</dependency>

2、方法

public static void pushNotice(String type, PushMessage pushMessage, String typeName) {
        String alias = pushMessage.getTarget();
        String title = "您有一条消息";
        if (pushMessage.getConvType() == 0) {
            title = pushMessage.getSenderName();
        } else if (pushMessage.getConvType() == 1) {
            title = pushMessage.getTargetName();
        }
        String context = pushMessage.pushContent;
        Map<String, String> extras = new HashMap<>();
        extras.put("content", new Gson().toJson(pushMessage));
        extras.put("type", "1");
        JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
        PushPayload.Builder builder = PushPayload.newBuilder();
        //设置接受的平台,all为所有平台,包括安卓、ios、和微软的
        builder.setPlatform(Platform.all());
        //设置如果用户不在线、离线消息保存的时间
        Options options = Options.sendno();
        options.setTimeToLive(time_to_live);
        builder.setOptions(options);
        //设置推送方式
        if (type != null) {
            if (type.equals("alias")) {
                builder.setAudience(Audience.alias(alias));
            } else if (type.equals("tag")) {
                builder.setAudience(Audience.tag(alias));
            }
        } else {//Audience设置为all,说明采用广播方式推送,所有用户都可以接收到
            builder.setAudience(Audience.all());
        }
        //设置为采用通知的方式发送消息
        // builder.setNotification(Notification.alert(title));

        Notification notification = null;
        if (typeName.equals("android")) {
            notification = Notification.android(context, title, extras);
        }
        if (typeName.equals("ios")) {
            notification = Notification.ios(context, extras);
        }
        builder.setNotification(notification);
        //builder.setNotification(Notification.alert(alert));
        PushPayload pushPayload = builder.build();
        try {
            //进行推送,实际推送就在这一步
            PushResult pushResult = jPushClient.sendPush(pushPayload);
            System.out.println(pushResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

posted on 2020-05-26 16:06  fuanfei  阅读(784)  评论(0)    收藏  举报