极光推送

一、极光推送基本信息

  访问地址:http://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/

  

二、代码实现

  场景:调用极光服务器推送消息

JiguangPromotion :发送的Util,可以在java的任何地方调用
package com.guduo.common.jiguan;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
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 com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloopen.rest.sdk.utils.encoder.BASE64Encoder;

@SuppressWarnings("deprecation")
public class JiguangPromotion {
    
    //设置推送平台("android", "ios", "winphone", "all")
    private String platform = "android";
    
    //AppKey
    private String appKey = "9103398f8e3f1ea149657d01";
    
    //Master Secret
    private String masterSecret = "d95532356bfd55d4d907bdbc";
    
    private String sendUrl = "https://api.jpush.cn/v3/push";
    
    /**
     * 极光推送
     * @param sendType:推送类型(1:通知栏推送,2:透析推送,3:两种都传),可选
     * @param title:推送标题,可选
     * @param content:推送内容,必传
     * @param builderId:通知栏展示样式,可选
     * @param type:业务模块,必传
     * @param cmdID:具体业务码,必传
     * @param audience:接收人集合,则推送给发送全部
     * @return response:{"code":"返回的操作码","message":"返回的描述信息"}
     *                 
     */
    public String sendMsg(String sendType,String title,String content,int builderId,String type,String cmdID,JSONArray audience)
    {
        Map<String,String> response = new HashMap<String, String>();
        //校验参数合法性
        String[] params = {sendType,content,type,cmdID};
        if(checkParams(params))
        {
            response.put("code", "0001");
            response.put("message", "入参不满足推送的条件");
        }
        //封装参数
        Map<String,Object> map = dealParams(sendType, title, content, builderId, type, cmdID,audience);
        //HTTP鉴权
        String auth = authorization();
        //调用发送
        response = httpPost(sendUrl, JSONObject.toJSONString(map),true,auth);
        return JSONObject.toJSONString(response);  
    }
    
    private Map<String, Object> dealParams(String sendType,String title,String content,int builderId,String type,String cmdID,JSONArray audience)
    {
        Map<String,Object> map = new HashMap<String,Object>();
        //设置推送平台
        map.put("platform", platform);
        //设置推送目标(别名、标签、注册ID、分群、广播)
        if(null == audience)
        {
            map.put("audience", "all");
        }else{
            map.put("audience", audience);
        }
        //设置扩张字段,用于业务
        Map<String, Object> extras = new HashMap<String, Object>(); //定义扩展字段
        extras.put("type", type);
        extras.put("cmdID", cmdID);
        //通知栏推送
        if(sendType.equals(JiGuangSendEnum.JIGUANG_SEND_NOTIFICATION.type) || sendType.equals(JiGuangSendEnum.JIGUANG_SEND_ALL.type))
        {
            Map<String, Object> notification = new HashMap<String, Object>();
            notification.put("alert", content);//内容可以为空字符串,则表示不展示到通知栏。
            notification.put("title", title);//如果指定了,则通知里原来展示 App名称的地方,将展示成这个字段。
            if(0!=builderId)
            {
                notification.put("builder_id", builderId);//通知栏样式ID,Android SDK 可设置通知栏样式,这里根据样式 ID 来指定该使用哪套样式。
            }
            notification.put("extras", extras);
            map.put("notification", notification);
        }
        //透析推送,此部分内容不会展示到通知栏上,JPush SDK 收到消息内容后透传给 App。需要 App 自行处理
        if(sendType.equals(JiGuangSendEnum.JIGUANG_SEND_MESSAGE.type) || sendType.equals(JiGuangSendEnum.JIGUANG_SEND_ALL.type)){
            Map<String, Object> message = new HashMap<String, Object>();
            message.put("title", title);//消息标题(可选)
            message.put("msg_content", content);//消息内容本身(必填)
            message.put("extras", extras);//扩展字段(可选)
            map.put("message", message);
        }
        return map;
    }
    
    /**
     * 鉴权
     * @return
     */
    private String authorization()
    {
        String auth = appKey+":"+masterSecret;
        return new BASE64Encoder().encode(auth.getBytes());
    }
    
    /**
     * 
     * @param url:请求地址
     * @param jsonParam:请求参数
     * @param noNeedResponse:是否需要返回结果
     * @param auth:认证信息
     * @return
     */
    private Map<String, String> httpPost(String url,String params, boolean noNeedResponse,String auth)
    {
        //返回结果
        Map<String, String> map = new HashMap<String, String>();
        //post请求返回结果
        @SuppressWarnings({ "resource"})
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        try {
            if (StringUtils.isNotEmpty(params)) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(params, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            method.setHeader("Authorization", " Basic "+auth);
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            //返回的Code
            map.put("code", String.valueOf(result.getStatusLine().getStatusCode()));
            //返回的结果消息
            map.put("message", EntityUtils.toString(result.getEntity()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 非空校验
     * @param params
     * @return
     */
    private boolean checkParams(String[] params)
    {
        for(String param:params){
            if(StringUtils.isEmpty(param))
            {
                return true;
            }
        }
        return false;
    }
    
    /*public static void main(String[] args) {
        System.out.println(new JiguangPromotion().sendMsg("1", "测试标题", "测试内容", 0, "0003", "3001",null));
    }*/
}

    JiGuangSendEnum:定义发送类型

package com.guduo.common.jiguan;

/**
 * 定义极光发送类型
 * @author shb
 *
 */
public enum JiGuangSendEnum {
    
    JIGUANG_SEND_NOTIFICATION("1"), //通知栏推送
    
    JIGUANG_SEND_MESSAGE("2"), //透析推送
    
    JIGUANG_SEND_ALL("3"); //通知栏推送+透析推送
    
    /**
     * 发送类型
     */
    public String type;
    
    private JiGuangSendEnum(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
    
}

 

    

   Controller:支持web请求调用

/**
     * 极光推送
     * @param params
     * @return
     */
    @ResponseBody
    @RequestMapping(value="jiguang",method=RequestMethod.POST)
    public String jiGuangPromotion(@RequestBody JiGuangParams params )
    {
        ResponseData data = new ResponseData();
        //校验非空,满足条件才能执行发送
        String[] checkParams = {params.getSendType(),params.getContent(),params.getCmdID(),params.getType()};
        if(checkParams(checkParams))
        {
            data.setCode(CodeEnum.NOPARAM.code);
            return JSONObject.toJSONString(data);
        }
        String message = new JiguangPromotion().sendMsg(params.getSendType(), params.getTitle(), params.getContent(), params.getBuilderId(), params.getType(), params.getCmdID(), params.getAudience());
        return message;
    }
  JiGuangParams :接收实体
package com.guduo.common.web.sendPromotion;

import com.alibaba.fastjson.JSONArray;

/**
 * 极光传送格式定义
 * @author shb
 *
 */
public class JiGuangParams {

    /**
     * 推送类型(1:通知栏推送,2:透析推送)
     */
    private String sendType;
    
    /**
     * 推送标题
     */
    private String title;
    
    /**
     * 推送内容
     */
    private String content;
    
    /**
     * 通知栏展示样式
     */
    private int builderId;
    
    /**
     * 业务模块
     */
    private String type;
    
    /**
     * 具体业务码
     */
    private String cmdID;
    
    /**
     * 接收人,空则为发送给全部
     */
    private JSONArray audience;

    public String getSendType() {
        return sendType;
    }

    public void setSendType(String sendType) {
        this.sendType = sendType;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public int getBuilderId() {
        return builderId;
    }

    public void setBuilderId(int builderId) {
        this.builderId = builderId;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getCmdID() {
        return cmdID;
    }

    public void setCmdID(String cmdID) {
        this.cmdID = cmdID;
    }

    public JSONArray getAudience() {
        return audience;
    }

    public void setAudience(JSONArray audience) {
        this.audience = audience;
    }

}

 

 
posted @ 2016-11-26 19:30  刘广平  阅读(318)  评论(0)    收藏  举报