极光推送 使用实例 (一)服务端

最近一直在做后台开发,但心里还是总惦记着Android,感觉还是Android有意思。正好项目中要用到极光推送,今天抽空来记录下这两天的研究成果。

我们知道iOS有自己的推送服务,但很遗憾Android没有原生的推送服务,现在有很多第三方的推送服务,比如个推、极光、亚马逊、百度云、聚能等。今天我们就来研究下极光推送的后台服务器如何实现。

关键点:

1.首先最好是把极光官网Java后台服务器的demo下载下来,里面有我们需要的jar包,以及example.

2.极光推送的关键jpushClient = new JPushClient(masterSecret, appKey, 3);就是这个类。其中的参数需要我们从极光官网注册开发者,然后创建具体项目获取相应的两                 个key值。其中appKey值就是我们手机端对应的key值

3.极光推送给我们提供了很多种推送的方式,我们可以选择某一个平台进行推送(Android ,IOS ,Windows Phone),也可以全部推送;我们可以针对某个特别的用户进行推送(设置alisa),也可以针对特别的群体进行推送(设置tag),第三个参数是设置推送保留的时间,只要在有效时间内上线就可以收到推送信息

4. 极光推送现在都用https连接,提交请求是post,获取数据为get

ok 接下来就看服务端的实现(JAVA),JdPush推送方法+一个Servlet

:

[java] view plain copy

  1. package com.weiwend.jdpush;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import cn.jpush.api.JPushClient;
  5. import cn.jpush.api.common.resp.APIConnectionException;
  6. import cn.jpush.api.common.resp.APIRequestException;
  7. import cn.jpush.api.push.PushResult;
  8. import cn.jpush.api.push.model.Message;
  9. import cn.jpush.api.push.model.Options;
  10. import cn.jpush.api.push.model.Platform;
  11. import cn.jpush.api.push.model.PushPayload;
  12. import cn.jpush.api.push.model.audience.Audience;
  13. import cn.jpush.api.push.model.audience.AudienceTarget;
  14. import cn.jpush.api.push.model.notification.AndroidNotification;
  15. import cn.jpush.api.push.model.notification.IosNotification;
  16. import cn.jpush.api.push.model.notification.Notification;
  17. public class Jdpush {
  18. protected static final Logger LOG = LoggerFactory.getLogger(Jdpush.class);
  19. // demo App defined in resources/jpush-api.conf
  20. public static final String TITLE = "申通快递";
  21. public static final String ALERT = "祝大家新春快乐";
  22. public static final String MSG_CONTENT = "申通快递祝新老客户新春快乐";
  23. public static final String REGISTRATION_ID = "0900e8d85ef";
  24. public static final String TAG = "tag_api";
  25. public  static JPushClient jpushClient=null;
  26. public static void testSendPush(String appKey ,String masterSecret) {
  27. jpushClient = new JPushClient(masterSecret, appKey, 3);
  28. // HttpProxy proxy = new HttpProxy("localhost", 3128);
  29. // Can use this https proxy: https://github.com/Exa-Networks/exaproxy
  30. // For push, all you need do is to build PushPayload object.
  31. //PushPayload payload = buildPushObject_all_all_alert();
  32. //生成推送的内容,这里我们先测试全部推送
  33. PushPayload payload=buildPushObject_all_alias_alert();
  34. try {
  35. System.out.println(payload.toString());
  36. PushResult result = jpushClient.sendPush(payload);
  37. System.out.println(result+"................................");
  38. LOG.info("Got result - " + result);
  39. } catch (APIConnectionException e) {
  40. LOG.error("Connection error. Should retry later. ", e);
  41. } catch (APIRequestException e) {
  42. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  43. LOG.info("HTTP Status: " + e.getStatus());
  44. LOG.info("Error Code: " + e.getErrorCode());
  45. LOG.info("Error Message: " + e.getErrorMessage());
  46. LOG.info("Msg ID: " + e.getMsgId());
  47. }
  48. }
  49. public static PushPayload buildPushObject_all_all_alert() {
  50. return PushPayload.alertAll(ALERT);
  51. }
  52. public static PushPayload buildPushObject_all_alias_alert() {
  53. return PushPayload.newBuilder()
  54. .setPlatform(Platform.all())//设置接受的平台
  55. .setAudience(Audience.all())//Audience设置为all,说明采用广播方式推送,所有用户都可以接收到
  56. .setNotification(Notification.alert(ALERT))
  57. .build();
  58. }
  59. public static PushPayload buildPushObject_android_tag_alertWithTitle() {
  60. return PushPayload.newBuilder()
  61. .setPlatform(Platform.android())
  62. .setAudience(Audience.all())
  63. .setNotification(Notification.android(ALERT, TITLE, null))
  64. .build();
  65. }
  66. public static PushPayload buildPushObject_android_and_ios() {
  67. return PushPayload.newBuilder()
  68. .setPlatform(Platform.android_ios())
  69. .setAudience(Audience.tag("tag1"))
  70. .setNotification(Notification.newBuilder()
  71. .setAlert("alert content")
  72. .addPlatformNotification(AndroidNotification.newBuilder()
  73. .setTitle("Android Title").build())
  74. .addPlatformNotification(IosNotification.newBuilder()
  75. .incrBadge(1)
  76. .addExtra("extra_key", "extra_value").build())
  77. .build())
  78. .build();
  79. }
  80. public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
  81. return PushPayload.newBuilder()
  82. .setPlatform(Platform.ios())
  83. .setAudience(Audience.tag_and("tag1", "tag_all"))
  84. .setNotification(Notification.newBuilder()
  85. .addPlatformNotification(IosNotification.newBuilder()
  86. .setAlert(ALERT)
  87. .setBadge(5)
  88. .setSound("happy")
  89. .addExtra("from", "JPush")
  90. .build())
  91. .build())
  92. .setMessage(Message.content(MSG_CONTENT))
  93. .setOptions(Options.newBuilder()
  94. .setApnsProduction(true)
  95. .build())
  96. .build();
  97. }
  98. public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
  99. return PushPayload.newBuilder()
  100. .setPlatform(Platform.android_ios())
  101. .setAudience(Audience.newBuilder()
  102. .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
  103. .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
  104. .build())
  105. .setMessage(Message.newBuilder()
  106. .setMsgContent(MSG_CONTENT)
  107. .addExtra("from", "JPush")
  108. .build())
  109. .build();
  110. }
  111. }

可以看到上面我们推送平台设置的是所有平台,Audience设置为all(所有用户),这里key值和masterSecret值放在servlet中了。

servlet很简单,只要传入两个key值,调用该方法就可以

[java] view plain copy

  1. package com.weiwend.jdpush.servlet;
  2. import java.io.IOException;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import com.sun.org.apache.xml.internal.serializer.utils.Utils;
  8. import com.weiwend.jdpush.Jdpush;
  9. import com.weiwend.jdpush.utils.Base64Utils;
  10. /**
  11. * Servlet implementation class tuisong
  12. */
  13. public class tuisong extends HttpServlet {
  14. private static final long serialVersionUID = 1L;
  15. private static final String appKey ="84cf5ee2099c654aa03a5d70";
  16. private static final String masterSecret = "7cf23f25a41806d5fd29e3c5";
  17. public tuisong() {
  18. super();
  19. // TODO Auto-generated constructor stub
  20. }
  21. /**
  22. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  23. */
  24. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  25. Jdpush.testSendPush(appKey,masterSecret);
  26. System.out.println("sucess");
  27. }
  28. /**
  29. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  30. */
  31. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  32. // TODO Auto-generated method stub
  33. }
  34. }

最后来看下运行的结果,可以看到,提交数据是以json格式。如果返回{"msg_id":1663001319,"sendno":1981162191}这样数据说明推送已经成功发送

[java] view plain copy

  1. {"platform":"all","audience":"all","notification":{"alert":"祝大家新春快乐"},"options":{"sendno":1981162191,"apns_production":false}}
  2. {"msg_id":1663001319,"sendno":1981162191}................................
  3. sucess

源码分析:

JPushClient jpushClient = new JPushClient(masterSecret, appKey, 3);实际上是实例化了一下三个类

[java] view plain copy

  1. public JPushClient(String masterSecret, String appKey, int maxRetryTimes) {
  2. _pushClient = new PushClient(masterSecret, appKey, maxRetryTimes);
  3. _reportClient = new ReportClient(masterSecret, appKey, maxRetryTimes);
  4. _deviceClient = new DeviceClient(masterSecret, appKey, maxRetryTimes);
  5. }

PushPayload payload = buildPushObject_all_all_alert();,PushPayload类里包含了传递和返回的所有数据

[java] view plain copy

  1. public class PushPayload implements PushModel {
  2. private static final String PLATFORM = "platform";
  3. private static final String AUDIENCE = "audience";
  4. private static final String NOTIFICATION = "notification";
  5. private static final String MESSAGE = "message";
  6. private static final String OPTIONS = "options";
  7. private static final int MAX_GLOBAL_ENTITY_LENGTH = 1200;  // Definition acording to JPush Docs
  8. private static final int MAX_IOS_PAYLOAD_LENGTH = 220;  // Definition acording to JPush Docs
  9. private static Gson _gson = new Gson();
  10. private final Platform platform;
  11. private final Audience audience;
  12. private final Notification notification;
  13. private final Message message;
  14. private Options options;
  15. private PushPayload(Platform platform, Audience audience,
  16. Notification notification, Message message, Options options) {
  17. this.platform = platform;
  18. this.audience = audience;
  19. this.notification = notification;
  20. this.message = message;
  21. this.options = options;
  22. }

PushResult result = jpushClient.sendPush(payload);可以看到就是sendPost方法,然后接受返回的数据

[java] view plain copy

  1. public PushResult sendPush(PushPayload pushPayload) throws APIConnectionException, APIRequestException {
  2. Preconditions.checkArgument(! (null == pushPayload), "pushPayload should not be null");
  3. if (_globalSettingEnabled) {
  4. pushPayload.resetOptionsTimeToLive(_timeToLive);
  5. pushPayload.resetOptionsApnsProduction(_apnsProduction);
  6. }
  7. ResponseWrapper response = _httpClient.sendPost(_baseUrl + PUSH_PATH, pushPayload.toString());
  8. return BaseResult.fromResponse(response, PushResult.class);
  9. }

另外我专门找了下sendNo如何生成的,其实就是随机生成的一个数字

[java] view plain copy

  1. public static Options sendno() {
  2. return newBuilder().setSendno(ServiceHelper.generateSendno()).build();
  3. }

[java] view plain copy

  1. public static int generateSendno() {
  2. return RANDOM.nextInt((MAX - MIN) + 1) + MIN;
  3. }

大家有兴趣也可以详细看一下代码的实现.

刚开始值直接下载的demo运行,一直提示Audience没有对应的用户,是引文Audience设置了别名alias,而用户里面并没有设置对应的alias,所以找不到对应的用户。

最后我们来看一张图,再深入理解下极光推送的原理

转自:http://blog.csdn.net/u014733374/article/details/43560983

时间: 2024-07-31 03:40:00

极光推送 使用实例 (一)服务端的相关文章

极光推送使用实例(二) Android客户端

上一篇简单介绍了极光推送在Java服务端的实现,如果感兴趣的可以看一下极光推送使用实例(一)JAVA服务端.这篇文章介绍下极光推送在Android客户端的实现. JPush Android SDK 是作为 Android Serivice 长期运行在后台的,从而创建并保持长连接,保持永远在线的能力.JPush Android SDK 由于使用自定义协议,协议体做得极致地小,流量消耗非常地小.电量方面,JPush Android SDK 经过持续地优化,尽可能减少不必要的代码执行:并且,长期的版本

用JPUSH极光推送实现服务端向安装了APP应用的手机推送消息(C#服务端接口)

这次公司要我们做一个功能,就是当用户成功注册以后,他登录以后要收到消息,当然这个消息是安装了我们的手机APP应用的手机咯. 极光推送的网站的网址是:https://www.jpush.cn/ 极光推送的官方API以及帮助文档都在这里:http://docs.jpush.cn/display/dev/Index 其中服务端的接口以及示例代码都在这里:http://docs.jpush.cn/display/dev/Server-SDKs 大家有兴趣的可以看看,因为这次我做的不是客户端APP,所以一

Ionic JPush极光推送 插件实例

1.需要去这里注册https://www.jiguang.cn 注册成功获取AppKey 备注填写应用包名规范点,在项目还要用那 2.创建ionic 项目 指定你注册时候的包名(假如:com.ionicframework.ltapp) ionic start  -i com.ionicframework.ltapp ltapp blank 3.添加JPush 插件 进入 项目目录下 cd  ltapp git clone https://github.com/jpush/jpush-phoneg

极光推送客户端和服务端相关文档

一.客户端: 二.服务端: 1.极光消息推送服务器端开发实现推送(上): http://blog.csdn.net/dawanganban/article/details/18770727?utm_source=tuicool 2.极光消息推送服务器端开发实现推送(下): http://blog.csdn.net/dawanganban/article/details/19029667?utm_source=tuicool 3.极光推送 使用实例 (一)服务端: http://blog.csdn

java SDK服务端推送 --极光推送(JPush)

网址:https://blog.csdn.net/duyusean/article/details/86581475 消息推送在APP应用中越来越普遍,来记录一下项目中用到的一种推送方式,对于Andriod它并没有自己的原生推送机制,一种简单的推送方式是采用第三方推送服务的方式,即通过嵌入SDK使用第三方提供的推送服务,主流的有百度云推送,极光推送,友盟,个推.亚马逊等等.本篇博文只介绍采用极光推送的方式.        如果你是一个新手,建议你先看完本篇博客,然后在去看官网,这样也许上手会快一

关于极光推送Jpush的demo

关于极光推送Jpush 推送是手机app必不可少的一样功能,这次由于公司项目需要研究了一下.由于推送一般写于服务端,所以对于不会Android的javaweb程序员要写出一个完整的demo是一件很头痛的事情.所以我就在这里从头到尾写一个例子以示参考.由于我也不懂Android 只是由于项目需要百度了一个demo,当中有很多不足的地方忘各位大神指正. 一.首先先简单的介绍一下什么是极光推送 ①为什么需要推送:为了解决数据同步的问题,在手机平台上,常用的方法有2种.一种是定时去服务器上查询数据,也叫

【android极光推送】—从客户端到后台,一文通吃

前记 推送原理浅析 平台说明 概念解释 推送的三种实现方式 客户端直接向推送服务方发送Http请求 项目服务器通过Http转发推送请求至推送服务方 项目服务端使用SDK进行功能集成 关于推送的种类概述 android客户端初步实现 集成SDK说明 集成步骤 1下载官方提供的SDK集成包 2手动导入SDK 3在极光的官网创建一个应用 4编写一个MyApplication类初始化SDK 5配置 AndroidManifestxml wampServer服务端配置 配置推送SDK 通过composer

使用极光推送实现分组发送和服务端集成

推送功能在手机应用开发中越来越重要,几乎成为所有App必备的功能,由于Android本身没有消息推送机制,通常采用的是基于XMPP协议的推送,但这种开发很麻烦,因此在市场上应运而生了提供消息推送服务的诸多产品,例如:百度云.个推.极光等. 极光推送正是一个整合了Android推送.iOS推送的统一推送服务平台.下面讲解一下如何使用极光实现消息推送应用,并重点讲解一下如何实现向分组发送消息及推送服务端和自身应用集成,具体实现过程如下: 目录: 一.注册应用 二.环境搭建 三.Android开发,实

使用极光推送(www.jpush.cn)向安卓手机推送消息【服务端向客户端主送推送】C#语言

链接网址:http://www.cnblogs.com/yangwujun/p/5973120.html 在VisualStudio2010中新建网站JPushAndroid.添加引用json帮助类库Newtonsoft.Json.dll. 在web.config增加appkey和mastersecret,可以在极光官网www.jpush.cn申请.web.config源码: <?xml version="1.0"?> <!-- 有关如何配置 ASP.NET 应用程序