极光推送JAVA代码示例

一、 准备工作

1. 登录极光推送官网https://www.jpush.cn/,注册账号并登录

2. 创建应用
创建应用过程,详见百度经验:http://jingyan.baidu.com/article/4f34706ecf2664e387b56d98.html
3. 获取appkey和masterSecret
 
二、 服务端开发
1. 创建java web工程
2. 在WEB-INF路径下的lib路径下,导入相关jar包,相关jar包可以在极光推送官网获取。
 
3. 到官网下载java服务器sdk压缩包。
 
4. 将官网例子中\jpush-api-java-client-3.2.9\src\main\java路径下cn文件夹整个拖入到src中。
 
注1:这是一种折中方案,我看大神们基本没有导入这个包,也正常使用了,但是我如果不这样做,就会报各种import错误,也是无奈之举
 
注2:这一过程可能会报错,不要紧张,一个个的点进去看,应该都是告诉你@overRide标签有问题,删掉就好
5. 创建一个新的包com.weiwend.jdpush,创建class文件Jdpush.java

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

package com.weiwend.jdpush.servlet; import Java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sun.org.apache.xml.internal.serializer.utils.Utils; import com.weiwend.jdpush.Jdpush; import cn.jpush.*; /** * Servlet implementation class tuisong */ public class tuisong extends HttpServlet { private static final long serialVersionUID = 1L; private static final String appKey ="84cf5ee2099c654aa03a5d70"; private static final String masterSecret = "7cf23f25a41806d5fd29e3c5"; public tuisong() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Jdpush.testSendPush(appKey,masterSecret); System.out.println("sucess"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }

 
7. 修改web.xml,增加servlet描述

<servlet> <servlet-name >tuisong</servlet-name> <servlet-class>com.weiwend.jdpush.servlet.tuisong</servlet-class> </servlet> <servlet-mapping>   <servlet-name >tuisong</servlet-name>   <url-pattern>/tuisong</url-pattern> </servlet-mapping>

8. 修改index.jsp,增加servlet调用

<form action="tuisong" method="get">  <input type="text" name="username"></input> <input type="password" name="userpassword"></input> <br><input type="submit" value="denglu">

9. 将项目部署到tomcat下,启动tomcat
 
 
10. 通过网页进行访问,触发servlet
 
 
 点击登录按钮,触发servlet。界面样式就不改了,我相信除了处女座的程序员,没有人会在意这个。
11. 在console中查看推送结果。

log4j:WARN No appenders could be found for logger (cn.jpush.api.common.connection.NativeHttpClient). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. {"platform":"all","audience":"all","notification":{"alert":"祝大家新春快乐"},"options":{"sendno":34919015,"apns_production":false}} {"msg_id":3270259240,"sendno":34919015}................................ sucess

发送失败的原因是因为我们的应用并没有绑定某一个具体的客户端应用,所以推送失败了。但是本地服务器与推送服务器之间的通讯是完好的。

 

posted @ 2018-06-19 10:46  丁国丰  阅读(5772)  评论(0编辑  收藏  举报