极光推送-Java后台实现方式一:Http API
原创作品,可以转载,但是请标注出处地址http://www.cnblogs.com/V1haoge/p/6439313.html
Java后台实现极光推送有两种方式,一种是使用极光推送官方提供的推送请求API:https://api.jpush.cn/v3/push,另一种则是使用官方提供的第三方Java SDK,这里先进行第一种方式推送的实现代码:
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 com.alibaba.fastjson.JSONArray;
import net.sf.json.JSONObject;
import sun.misc.BASE64Encoder; /**
* java后台极光推送方式一:使用Http API
* 此种方式需要自定义http请求发送客户端:HttpClient
*/
@SuppressWarnings({ "deprecation", "restriction" })
public class JiguangPush {
private static final Logger log = LoggerFactory.getLogger(JiguangPush.class);
private String masterSecret = "xxxxxxxxxxxxxxxxxxxx";
private String appKey = "xxxxxxxxxxxxxxxxxxx";
private String pushUrl = "https://api.jpush.cn/v3/push";
private boolean apns_production = true;
private int time_to_live = 86400;
private static final String ALERT = "推送信息";
/**
* 极光推送
*/
public void jiguangPush(){
String alias = "123456";//声明别名
try{
String result = push(pushUrl,alias,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());
}
log.info("针对别名为" + alias + "的信息推送成功!");
}catch(Exception e){
log.error("针对别名为" + alias + "的信息推送失败!",e);
}
} /**
* 组装极光推送专用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();
alias1.add(alias);
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);
} 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;
}
}
以上代码中使用的是第一种方式实现推送,下面介绍第二种方式:使用java SDK
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
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.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification; /**
* java后台极光推送方式二:使用Java SDK
*/
@SuppressWarnings({ "deprecation", "restriction" })
public class JiguangPush {
private static final Logger log = LoggerFactory.getLogger(JiguangPush.class);
private static String masterSecret = "xxxxxxxxxxxxxxxxx";
private static String appKey = "xxxxxxxxxxxxxxxx";
private static final String ALERT = "推送信息";
/**
* 极光推送
*/
public void jiguangPush(){
String alias = "123456";//声明别名
log.info("对别名" + alias + "的用户推送信息");
PushResult result = push(String.valueOf(alias),ALERT);
if(result != null && result.isResultOK()){
log.info("针对别名" + alias + "的信息推送成功!");
}else{
log.info("针对别名" + alias + "的信息推送失败!");
}
} /**
* 生成极光推送对象PushPayload(采用java SDK)
* @param alias
* @param alert
* @return PushPayload
*/
public static PushPayload buildPushObject_android_ios_alias_alert(String alias,String alert){
return PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
.setAudience(Audience.alias(alias))
.setNotification(Notification.newBuilder()
.addPlatformNotification(AndroidNotification.newBuilder()
.addExtra("type", "infomation")
.setAlert(alert)
.build())
.addPlatformNotification(IosNotification.newBuilder()
.addExtra("type", "infomation")
.setAlert(alert)
.build())
.build())
.setOptions(Options.newBuilder()
.setApnsProduction(false)//true-推送生产环境 false-推送开发环境(测试使用参数)
.setTimeToLive(90)//消息在JPush服务器的失效时间(测试使用参数)
.build())
.build();
}
/**
* 极光推送方法(采用java SDK)
* @param alias
* @param alert
* @return PushResult
*/
public static PushResult push(String alias,String alert){
ClientConfig clientConfig = ClientConfig.getInstance();
JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
PushPayload payload = buildPushObject_android_ios_alias_alert(alias,alert);
try {
return jpushClient.sendPush(payload);
} catch (APIConnectionException e) {
log.error("Connection error. Should retry later. ", e);
return null;
} catch (APIRequestException e) {
log.error("Error response from JPush server. Should review and fix it. ", e);
log.info("HTTP Status: " + e.getStatus());
log.info("Error Code: " + e.getErrorCode());
log.info("Error Message: " + e.getErrorMessage());
log.info("Msg ID: " + e.getMsgId());
return null;
}
}
}
可以看出使用Java SDK实现推送的方式很简单,代码量也少,理解起来也不难,官方提供的SDK中将很多内容都实现了,我们只是需要配置一下信息,然后发起推送即可。需要注意的是使用第二种方式,需要导入极光官网提供的jar包。
直接在maven中的pom文件中加入:
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.2.15</version>
</dependency>
注意:在这里极有可能会出现jar包冲突:具体哪个包我也忘记了,好像是个日志包,找到后删除即可,我曾经记录过这个jar包冲突问题,详见jar包冲突解决。
原本我们项目中也是采用第二种方式实现的,但是最后在提交代码时发现一个问题,那就是虽然我们只是带导入了官网提供的那个jar包,但是最后一统计,竟然无缘无故增多了80+个jar包,如此多的jar包提交过于臃肿,而且不现实,所以才临时改变方案,采用第一种方式进行编码。
代码中采用的是别名方式进行推送,需要在在手机APP端进行别名设置,最好就是在用户登录之后就设置好,这样只要用户登录一次,它的绑定别名就可以保存到极光服务器,而我们推送时,指定这个别名,就能将信息推送到对应用户的手机上。
其实我们发起推送请求,只是将信息发送到了极光服务器之上,这个信息有一个保存时限,默认一天,只要用户使用手机APP登录系统,极光服务器就会将信息自动推送到对应别名的手机上,由此可见,信息并非由我们后台直接推送到手机,而是通过极光服务器这个中转站,而这正式极光的工作。
注意:这里告知一个技巧,这个别名设置的时候,其实直接将用户ID设置为别名即可,既方便,又安全,不用再去想办法生成一个唯一的串来进行标识,甚至需要在后台数据库中用户表中新增字段。
极光推送-Java后台实现方式一:Http API的更多相关文章
- 极光推送>>java SDK服务端集成后台项目(使用详解)
PS:如果你是第一次用推送,那就直接按照我的步骤来,再去看官方文档,这样,更容易能理解操作流程.还有——-请耐心看 极光文档(java SDK)请参考 [ 极光文档 ] 步骤一: 首先,你必须在 [极 ...
- JPush极光推送 Java调用服务器端API开发
极光推送是:使得开发者可以即时地向其应用程序的用户推送通知或者消息,与用户保持互动,从而有效地提高留存率,提升用户体验.简单的说就是通过JPush后台管理网站进行app消息的推送.可以让用户及时 ...
- 极光推送JAVA代码示例
一. 准备工作 1. 登录极光推送官网https://www.jpush.cn/,注册账号并登录 2. 创建应用 创建应用过程,详见百度经验:http://jingyan.baidu.com/arti ...
- 极光推送消息——Alias别称方式(Andirod)
1.pom文件引入相关jar包 <!--极光推送消息start--> <dependency> <groupId>net.sf.json-lib</group ...
- 总结:极光推送java服务端(1)
遇到的问题: 1.怎么用极光推送 2.极光推送发送失败报错 返回{ } 3.透传和推送区别以及怎么设置 我的解决方案: 问题1.极光推送类里面有不同的方法,需要发给那些人就调用相应的方法.有安卓.io ...
- 极光推送java代码
package com.zheng.cms.web.jpush.util; import cn.jpush.api.JPushClient; import cn.jpush.api.common.AP ...
- JPush极光推送Java服务器端实例
import cn.jpush.api.JPushClient; import cn.jpush.api.common.resp.APIConnectionException; import cn.j ...
- JPush极光推送Java服务器端API
// 对android和ios设备发送 JPushClient jpush = new JPushClient(masterSecret, appKey); // 对android和ios设备发送 ...
- 极光推送经验之谈-Java后台服务器实现极光推送的两种实现方式
原创作品,可以转载,但是请标注出处地址http://www.cnblogs.com/V1haoge/p/6439313.html Java后台实现极光推送有两种方式,一种是使用极光推送官方提供的推送请 ...
随机推荐
- github上一些酷炫效果
转自:http://blog.csdn.net/shulianghan/article/details/18046021 主要介绍那些不错个性化的View,包括ListView.ActionBar.M ...
- 谈谈Session会话和Cookie
Session Session在我们的网络应用中就是一种客户端与服务器端保持状态的解决方案 Session对象,就是客户端浏览器与服务器之间建立的互动信息状态.每一个不同的用户连接将得到不同的Sess ...
- win8.1 64位+oracle11g R2 64位 +powerdesigner破解版 64位+PL/SQL
安装时搜索了很多帖子,很多就是复制粘贴(完全不需要什么IP,host),有的版本不对,有的版本太老,今天决定贴出自己的处女贴 oracle的安装很简单,不需要说什么了,PL/SQL真是恶心死 orac ...
- PHP新手之学习类与对象(4)
五.范围解析操作符(::) 范围解析操作符(也可称作 Paamayim Nekudotayim)或者更简单地说是一对冒号,可以用于访问静态成员.方法和常量,还可以用于覆盖类中的成员和方法. 当在类的外 ...
- Emmet插件详解
http://www.ithao123.cn/content-10512551.html (webstorm的css编写插件)Emmet:HTML/CSS代码快速编写神器 [摘要:Emmet的前身 ...
- 解决Centos 7 下 tomcat字体异常 Font '宋体' is not available to the JVM
错误提示: SEVERE: Servlet.service() for servlet [example] in context with path [/myproject] threw except ...
- ILSpy .NET反编译工具下载地址
官方下载: http://ilspy.net/ 中文版下载地址: http://www.fishlee.net/soft/ilspy_chs/#C-310
- C# 启动停止SQLServer数据库服务器
C#启动停止SQL数据库服务方法之一: 在命令行里填写命令:net start/stop mssqlserver C#启动停止SQL数据库服务方法之二: 通过C#代码实现: class Program ...
- Ninja介绍
什么是Ninja 在Unix/Linux下通常使用Makefile来控制代码的编译,但是Makefile对于比较大的项目有时候会比较慢,看看上面那副漫画,代码在编译都变成了程序员放松的借口了.所以这个 ...
- Chrome中java因过期而遭到阻止
http://www.cnblogs.com/jifeng/p/3453322.html 在Chrome快捷方式图标上右击,选[属性],然后在[目标]一栏的末尾添加这么一段命令(flag): --al ...