一、代码实现

1.配置类—Env.java

package com.ray.jpush.config;

/**@desc  : 极光推送接入配置
*
* @author: shirayner
* @date : 2017年9月27日 下午4:57:36
*/ public class Env { /**
* 1.极光推送后台APPKEY,MASTER_SECRET
*/
public static final String APP_KEY = "354fb5c3dd4249ec11bc545d";
public static final String MASTER_SECRET = "8976605bf8a9ef9d8d97a8c2";
}

2.消息服务类—MessageService.java

package com.ray.jpush.service.message;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ray.jpush.util.CommonUtil;
import com.ray.jpush.util.HttpHelper; /**@desc : 极光推送消息服务
*
* @author: shirayner
* @date : 2017年11月29日 下午2:24:16
*/
public class MessageService {
private static final Logger log= LogManager.getLogger(MessageServiceTest.class); //1.发送通知
private static final String SEND_NOTIFICATION_URL="https://api.jpush.cn/v3/push"; /**
* @desc : 1.调用极光API
*
* @param url 接口url
* @param registration_id 注册id
* @param alert 通知内容
* @param appKey
* @param masterSecret
* @return
* JSONObject
*/
public static JSONObject sendNotification(String registration_id,String alert,String appKey,String masterSecret) { String base64_auth_string = CommonUtil.encryptBASE64(appKey + ":" + masterSecret);
String authorization = "Basic " + base64_auth_string; String data=generateJson(registration_id,alert).toString(); log.debug("authorization:"+authorization);
log.debug("data:"+data); return HttpHelper.doPost(SEND_NOTIFICATION_URL, data, authorization);
} /**
* @desc : 2.拼装请求json
*
* @param registration_id 注册id
* @param alert 通知内容
* @return
* JSONObject
*/
private static JSONObject generateJson(String registration_id,String alert){
JSONObject json = new JSONObject(); JSONArray platform = new JSONArray(); //1.推送平台设置
platform.add("android");
platform.add("ios"); JSONObject audience = new JSONObject(); //2.推送设备指定,即推送目标
JSONArray registrationIdList = new JSONArray();
registrationIdList.add(registration_id);
audience.put("registration_id", registrationIdList); JSONObject notification = new JSONObject(); //3.通知内容
JSONObject android = new JSONObject(); //3.1 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();//3.2 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); json.put("platform", platform);
json.put("audience", audience);
json.put("notification", notification); return json; } }

3.HttpHelper工具类—HttpHelper.java

package com.ray.jpush.util;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; /**
* HTTP请求工具类
*/
public class HttpHelper { /**
* @desc :1.发送POST请求-极光推送
*
* @param url 接口url
* @param data 请求包体
* @param authorization 验证字段,Authorization: Basic base64_auth_string
* 其中 base64_auth_string 的生成算法为:base64(appKey:masterSecret)
* 即,对 appKey 加上冒号,加上 masterSecret 拼装起来的字符串,再做 base64 转换。
* @return
* @throws Exception
* JSONObject
*/
public static JSONObject doPost(String url, String data ,String authorization) {
//1.生成一个请求
HttpPost httpPost = new HttpPost(url); //2.配置请求属性
//2.1 设置请求超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
httpPost.setConfig(requestConfig);
//2.2 设置数据传输格式-json
httpPost.addHeader("Content-Type", "application/json");
//2.3 设置Authorization
httpPost.addHeader("Authorization", authorization.trim()); //2.3 设置请求实体,封装了请求参数
StringEntity requestEntity = new StringEntity(data, "utf-8");
httpPost.setEntity(requestEntity); //3.发起请求,获取响应信息
//3.1 创建httpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null; try {
//3.3 发起请求,获取响应
response = httpClient.execute(httpPost, new BasicHttpContext()); if (response.getStatusLine().getStatusCode() != 200) { System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode()
+ ", url=" + url);
return null;
} //获取响应内容
HttpEntity entity = response.getEntity();
if (entity != null) {
String resultStr = EntityUtils.toString(entity, "utf-8");
System.out.println("POST请求结果:"+resultStr); //解析响应内容
JSONObject result = JSON.parseObject(resultStr); //请求失败
if (result.getInteger("errcode")!=null && 0 != result.getInteger("errcode")) { System.out.println("request url=" + url + ",return value=");
System.out.println(resultStr);
int errCode = result.getInteger("errcode");
String errMsg = result.getString("errmsg"); try {
throw new Exception("error code:"+errCode+", error message:"+errMsg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //请求成功
} else {
return result;
} }
} catch (IOException e) {
System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
e.printStackTrace();
} finally {
if (response != null) try {
response.close(); //释放资源 } catch (IOException e) {
e.printStackTrace();
}
} return null;
} }

4.通用工具类—CommonUtil.java

package com.ray.jpush.util;

import sun.misc.BASE64Encoder;

/**@desc  :
*
* @author: shirayner
* @date : 2017年11月29日 下午3:11:33
*/
public class CommonUtil { /**
* @desc :BASE64加密工具
*
* @param str 待加密字符串
* @return
* String
*/
public static String encryptBASE64(String str) {
byte[] key = str.getBytes();
BASE64Encoder base64Encoder = new BASE64Encoder();
String strs = base64Encoder.encodeBuffer(key);
return strs;
}
}

5.消息服务测试类—MessageServiceTest.java

package com.ray.jpush.service.message;

import org.junit.Test;

import com.ray.jpush.config.Env;

/**@desc  : 极光推送测试类
*
* @author: shirayner
* @date : 2017年11月29日 下午3:54:42
*/
public class MessageServiceTest { /**
* @desc :1.发送通知
*
* void
*/
@Test
public void testSendNotification() {
String registration_id="121c83f760211fa5944";
//String alert="hello,my honey!";
String alert="您好:\\n 于岩军在2017-11-15提出了一张金额为5的费用报销单 BX10017110076 ,需要审批! \\n\\n\\n===================================================================\\n\\n秒针费用管理系统\\n\\n本邮件由系统自动发送,请勿回复。";
String appKey=Env.APP_KEY;
String masterSecret=Env.MASTER_SECRET; MessageService.sendNotification(registration_id, alert, appKey, masterSecret);
}
}

二、参考资料

1.极光推送经验之谈-Java后台服务器实现极光推送的两种实现方式

极光推送_总结_01_Java实现极光推送的更多相关文章

  1. AndroidStudio离线打包MUI集成JPush极光推送并在java后端管理推送

    1.AndroidStudio离线打包MUI 如何离线打包请参看上篇随笔<AndroidStudio离线打包MUI> 2.集成极光推送 官方文档:https://docs.jiguang. ...

  2. 做推送,怎么能不了解推送的 4 种消息形式呢?( Android 篇)

    极光推送是为 App 提供第三方推送服务的平台之一,它提供四种消息形式:通知,自定义消息,富媒体和本地通知. 笔者将基于官方说明与个人理解来谈一下这四种消息.本篇为 Android 篇,iOS 篇入口 ...

  3. 做推送,怎么能不了解推送的 4 种消息形式呢?(iOS 篇)

    极光推送是为 App 提供第三方推送服务的平台之一,它提供四种消息形式:通知,自定义消息,富媒体和本地通知.笔者将基于官方说明与个人理解来谈一下这四种消息.本篇为 iOS 篇,Android 篇入口. ...

  4. 本机号码认证黑科技:极光(JG)开发者服务推出“极光认证”新产品

    近日,中国领先的大数据服务商极光(JG)推出全新产品--极光认证JVerification.极光认证是极光针对APP用户注册登陆,二次安全验证等身份验证场景打造的一款本机号码认证SDK,验证用户提供的 ...

  5. 洛谷 P1454 圣诞夜的极光 == codevs 1293 送给圣诞夜的极光

    题目背景 圣诞夜系列~~ 题目描述 圣诞老人回到了北极圣诞区,已经快到12点了.也就是说极光表演要开始了.这里的极光不是极地特有的自然极光景象.而是圣诞老人主持的人造极光. 轰隆隆……烟花响起(来自中 ...

  6. HTML5服务器端推送事件 解决PHP微信墙推送问题

    问题描述 以前的文章中<PHP微信墙制作,开源>已经用PHP搭建了一个微信墙获取信息的服务器,然后我就在想推送技术应该怎么解决,上一篇已经用了.NET 的signalr做了一个微信墙,PH ...

  7. Android融合推送MixPush SDK集成多家推送平台,共享系统级推送,杀死APP也能收到推送

    消息推送是App运营的重要一环,为了优化消息推送成功率,降低电量和流量消耗,系统级的推送服务显得尤为重要.小米和魅族由此推出了自家的推送平台,在MIUI和Flyme上共享系统级推送服务,让APP在被杀 ...

  8. iOS原生推送(APNS)进阶iOS10推送图片、视频、音乐

    代码地址如下:http://www.demodashi.com/demo/13208.html 前言 我们首先要在AppDelegate里面进行iOS的适配,可以参考这篇文章 iOS原生推送(APNS ...

  9. 【开源毕设】一款精美的家校互动APP分享——爱吖校推 [你关注的,我们才推](持续开源更新3)附高效动态压缩Bitmap

    一.写在前面 爱吖校推如同它的名字一样,是一款校园类信息推送交流平台,这么多的家校互动类软件,你选择了我,这是我的幸运.从第一次在博客园上写博客到现在,我一次一次地提高博文的质量和代码的可读性,都是为 ...

随机推荐

  1. win10 uwp 入门

    UWP是什么我在这里就不说,本文主要是介绍如何入门UWP,也是合并我写的博客. 关于UWP介绍可以参见:http://lib.csdn.net/article/csharp/32451 首先需要申请一 ...

  2. Spring装配Bean之XML装配bean

    在Spring刚出现的时候,XML是描述配置的主要方式,在Spring的名义下,我们创建了无数行XML代码.在一定程度上,Spring成为了XML的同义词. 现在随着强大的自动化配置和Java代码的配 ...

  3. 在项目中集成jetty server

    为什么使用jetty 使用 tomcat 开发效率并不是太高,并且在eclipse有时两秒做更新,有时候又得手动去部署显得非常麻烦.折算我们可以使用 jetty server 由于 eclipse开发 ...

  4. Linux入门(10)——Ubuntu16.04使用pip3和pip安装numpy,scipy,matplotlib等第三方库

    安装Python3第三方库numpy,scipy,matplotlib: sudo apt install python3-pip pip3 install numpy pip3 install sc ...

  5. SPARK 创建新任务

    1.应用程序创建 SparkContext 的实例 sc 2.利用 SparkContext 的实例来创建生成 RDD 3.经过一连串的 transformation 操作,原始的 RDD 转换成为其 ...

  6. 关于github在客户端不小心删除新仓库,重建后无法上传解决方法

    不小心删除了如果直接在客户端重建一个不行,首先找出本地新仓库,删除,然后在重新再客户端建立一个. 但此时如果两仓库名字一样,会发现无法上传. 此时应该在网页打开github,点击进入之前删除的仓库(云 ...

  7. Java基础-运行原理及变量(01)

    java运行原理 手动编写java文件由编译器编译成.class文件,再由解释器翻译class文件成机器语言运行. Java中注释分类 单行注释格式: //注释文字多行注释格式: /* 注释文字 */ ...

  8. C# 8.0的三个令人兴奋的新特性

    C# 语言是在2000发布的,至今已正式发布了7个版本,每个版本都包含了许多令人兴奋的新特性和功能更新.同时,C# 每个版本的发布都与同时期的 Visual Studio 以及 .NET 运行时版本高 ...

  9. SpringBoot初体验(续)

    1.如果你还不知道SpringBoot的厉害之处,或者你不知道SpringBoot的初级用法,请移步我的上一篇文章,传送门 2.SpringBoot中的表单验证 所谓验证,无非就是检验,对比,正如ja ...

  10. js接收html传值

    var obj = document.getElementById("orgName");无法获取输入框的值,获取的值为[object HTMLInputElement].用var ...