极光消息推送它们提供了两种方法,一种是访问https路径,还是一种是使用它们提供的sdk,下面是两种实例。
1.访问https主要代码块
/**
* 极光推送(使用Http API(jdk1.4不支持提供的Java SDK))
*
* MyEclipse Struts Creation date: 2018-8-9
*
* @author
*
*/
public class JpushUtil {
//public static volatile int volatileCount=0;
//测试账号(注册时会提供)
private final static String APP_KEY = "XXXX";
private final static String MASTER_SECRET = "XXXX";
//极光推送官方提供的推送请求API
private final static String PUSJ_URL = "https://api.jpush.cn/v3/push";
//APNs是否生产环境(True表示推送生产环境,False表示要推送开发环境)
private final static Boolean APNS_PRODUCTION = new Boolean(true);
//离线消息保留时长(默认 86400 (1 天),最长 10 天。设置为 0 表示不保留离线消息,只有推送当前在线的用户可以收到)
private final static Integer TIME_TO_LIVE = new Integer(86400);
/**
* 推送方法-调用极光API
*
* @param reqUrl
* @param alias
* @param alert
* @return result
*/
public static String push(String alias, Object alert,HashMap map) throws Exception {
//if(volatileCount==0){
SSL.disableChecks();//忽略证书的验证
//volatileCount++;
//}
String base64_auth_string = encryptBASE64(APP_KEY + ":" + MASTER_SECRET);
String authorization = "Basic " + base64_auth_string;
return sendPostRequest(generateJson(alias, alert,map).toString(), "UTF-8",
authorization);
}
/**
* BASE64加密工具
* @param str
* @return
*/
public static String encryptBASE64(String str) {
byte[] key = str.getBytes();
BASE64Encoder base64Encoder = new BASE64Encoder();
String strs = base64Encoder.encodeBuffer(key);
return strs;
}
/**
* 组装极光推送专用json串
*
* @param alias别名设置(标识一个用户)
* @param alert通知内容(会覆盖上级统一指定的 alert 信息)
* @return json
*/
public static JSONObject generateJson(String alias, Object alert,HashMap map) {
JSONObject extras = new JSONObject();//Android And Ios额外参数
extras.put("type", "infomation");
extras.put("XXX", map.get("XXX"));
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", new Integer(1));//通知栏样式ID
android.put("extras", extras);
JSONObject ios = new JSONObject();// ios通知内容
ios.put("alert", alert);
ios.put("sound", "default");//通知提示声音(无此字段,则此消息无声音提示)
ios.put("badge", "+1");//应用角标(不填,表示不改变角标数字)
ios.put("extras", extras);
notification.put("android", android);
notification.put("ios", ios);
JSONObject options = new JSONObject();// 设置参数
options.put("time_to_live",TIME_TO_LIVE);
options.put("apns_production", APNS_PRODUCTION);
json.put("platform", platform);
//json.put("audience", "all");//广播推送所以用户
json.put("audience", audience);
json.put("notification", notification);
json.put("options", options);
return json;
}
/**
* 发送Post请求(json格式)
*
* @param reqURL
* @param data
* @param encodeCharset
* @param authorization
* @return result
*/
public static String sendPostRequest( String data,
String encodeCharset, String authorization) throws Exception {
HttpPost httpPost = new HttpPost(PUSJ_URL);
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) {
System.out.println("请求通信[" + PUSJ_URL + "]时偶遇异常,堆栈轨迹如下");
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
return result;
}
}
2.通过sdk来执行
/**
* 极光推送通用类
* @author 2018/09/17
*
*/
public class JpushClientUtil {
//推送账号
public static final String appKey = "XX";
public static final String masterSecret = "XX";
//APNs是否生产环境(True表示推送生产环境,False表示要推送开发环境)
private final static Boolean APNS_PRODUCTION = new Boolean(true);
//离线消息保留时长(默认 86400 (1 天),最长 10 天。设置为 0 表示不保留离线消息,只有推送当前在线的用户可以收到)
private final static Integer TIME_TO_LIVE = new Integer(86400);
protected static final Logger LOG = LoggerFactory.getLogger(JpushClientUtil.class);
/**
* 生成极光推送对象PushPayload(采用java SDK)
* @param alias 别名
* @param alter 推送内容
* @param msgContent
* @return
*/
public static PushPayload buildPushObject_android_ios_alias_alert(String alias, String alter,String msgContent){
return PushPayload.newBuilder().setPlatform(Platform.android_ios())// 推送安卓、IOS
.setAudience(Audience.alias(alias))//别名(可以是数组为并集,一次只能存1000个)
.setMessage(Message.newBuilder().setMsgContent(msgContent)// 消息内容
.addExtra("from", "JPush")//应用内消息通道
.build())
.setNotification(Notification.newBuilder()//notification:通知
.addPlatformNotification(IosNotification.newBuilder()// iOS
.setAlert(alter)//通知信息
.setBadge(0)//角标
.build())
.addPlatformNotification(AndroidNotification.newBuilder()// 安卓
.setAlert(alter)//通知信息
.build())
.build())
.setOptions(Options.newBuilder()
.setApnsProduction(APNS_PRODUCTION)
.setTimeToLive(TIME_TO_LIVE)
.build())
.build();
}
/**
* 极光推送方法(采用java SDK)
* @param bspMap
* @return
*/
public static HashMap<String, Object> jiguangPush(HashMap<String, Object> bspMap){
String alias = bspMap.get("ALIAS").toString();//别名
String alter = (String) bspMap.get("ALTER");//推送内容
JSONObject extras = new JSONObject();//推送的额外参数
extras.put("type", "infomation");
extras.put("XXX", bspMap.get("XXX"));//司机U代码
ClientConfig clientConfig = ClientConfig.getInstance();
PushResult result;//推送返回结果
HashMap<String, Object> bspRet = new HashMap<String, Object>();
JPushClient jpushClient = null;
try {
jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
PushPayload payload = buildPushObject_android_ios_alias_alert(alias,alter,new Gson().toJson(extras));
result = jpushClient.sendPush(payload);
Thread.sleep(1000);
if(result!=null && result.isResultOK()){
bspRet.put("result", "0");//推送成功
bspRet.put("error", "");
}else{
bspRet.put("result", "1");//推送失败
bspRet.put("error", "推送过程中失败!");
}
} catch (APIConnectionException e) {
bspRet.put("result", "1");
bspRet.put("error", "Connection error. Should retry later."+e);
LOG.error("Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
bspRet.put("result", "1");
bspRet.put("error", "Error response from JPush server. Should review and fix it."+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());
} catch (Exception e) {
bspRet.put("result", "1");
bspRet.put("error", "error it."+e);
LOG.error("Exception it. ", e);
}finally{
if(null !=jpushClient){
//请求结束后,调用 NettyHttpClient 中的 close 方法,否则进程不会退出。
jpushClient.close();
}
}
return bspRet;
}
}
使用maven的话需要加入:
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jiguang-common</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.6.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>