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;
}
}