百度推送代码备份

  1. 首先查看百度推送开发者文档,这里主要是用Java实现。

http://push.biadu.com

  1. Java项目jar 引用,这里使用maven管理jar 包。

HomePage : https://github.com/featherfly/sorm.git

<dependency>
    <groupId>cn.featherfly</groupId>
    <artifactId>bccs-api</artifactId>
    <version>3.0.1</version>
</dependency>
  1. 推送工具类封装,这里直接使用的文档中的demo示例:
package com.sun4j.app.web.plugins;

import com.alibaba.fastjson.JSONObject;
import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.baidu.yun.push.auth.PushKeyPair;
import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.constants.BaiduPushConstants;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.PushMsgToSingleDeviceRequest;
import com.baidu.yun.push.model.PushMsgToSingleDeviceResponse;
import com.baidu.yun.push.model.PushMsgToTagRequest;
import com.baidu.yun.push.model.PushMsgToTagResponse;
import com.sun4j.app.util.ConfigProperty;

public class PushUtil {
    public static void push2Android(String title, String description, String pushKey)
            throws PushClientException, PushServerException {
        String apiKey = ConfigProperty.getKey("API_KEY_Android");
        String secretKey = ConfigProperty.getKey("SECRET_KEY_Android");
        PushKeyPair pair = new PushKeyPair(apiKey, secretKey);
        BaiduPushClient pushClient = new BaiduPushClient(pair, BaiduPushConstants.CHANNEL_REST_URL);
        pushClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                System.out.println(event.getMessage());
            }
        });
        try {
            JSONObject notification = new JSONObject();
            notification.put("title", title);
            notification.put("description", description);
            notification.put("notification_builder_id", 0);
            notification.put("notification_basic_style", 4);
            notification.put("open_type", 1);
            JSONObject jsonCustormCont = new JSONObject();
            jsonCustormCont.put("key", "value");
            notification.put("custom_content", jsonCustormCont);

            PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest().addChannelId(pushKey)
                    .addMsgExpires(new Integer(3600)).addMessageType(1).addMessage(notification.toString())
                    .addDeviceType(3);
            PushMsgToSingleDeviceResponse response = pushClient.pushMsgToSingleDevice(request);
            System.out.println("msgId: " + response.getMsgId() + ",sendTime: " + response.getSendTime());
        } catch (PushClientException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                e.printStackTrace();
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                System.out.println(String.format("requestId: %d, errorCode: %d, errorMessage: %s", e.getRequestId(),
                        e.getErrorCode(), e.getErrorMsg()));
            }
        }
    }

    public static void push2TagIOS(String title, String description,String tag)
            throws PushClientException, PushServerException {
        String apiKey = ConfigProperty.getKey("API_KEY_IOS");
        String secretKey = ConfigProperty.getKey("SECRET_KEY_IOS");
        PushKeyPair pair = new PushKeyPair(apiKey, secretKey);
        BaiduPushClient pushClient = new BaiduPushClient(pair, BaiduPushConstants.CHANNEL_REST_URL);
        pushClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                System.out.println(event.getMessage());
            }
        });

        try {
            JSONObject notification = new JSONObject();
            JSONObject jsonAPS = new JSONObject();
            jsonAPS.put("alert", title);
            jsonAPS.put("sound", "ttt"); // 设置通知铃声样式,例如"ttt",用户自定义。
            notification.put("aps", jsonAPS);
            notification.put("description", description);
            PushMsgToTagRequest request = new PushMsgToTagRequest()
                    .addTagName(tag) //设置tag组
                    .addMsgExpires(new Integer(3600))
                    .addMessageType(1) // 1:通知,0:透传消息.默认为0  注:IOS只有通知.
                    .addMessage(notification.toString())
                    .addDeployStatus(1)// IOS,DeployStatus => 1: Developer, 2: Production.
                    .addDeviceType(4); // deviceType => 3:android, 4:ios
            PushMsgToTagResponse response = pushClient.pushMsgToTag(request);
            System.out.println("msgId: " + response.getMsgId() + ",sendTime: "
                    + response.getSendTime() + ",timerId: "
                    + response.getTimerId());
        } catch (PushClientException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                e.printStackTrace();
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                System.out.println(String.format("requestId: %d, errorCode: %d, errorMessage: %s", e.getRequestId(),
                        e.getErrorCode(), e.getErrorMsg()));
            }
        }
    }

    /**
     * 推送消息到标签组
     * 
     * @param title
     * @param description
     * @param pushKey
     * @param tag
     * @throws PushClientException
     * @throws PushServerException
     */
    public static void push2TagAndroid(String message, String tag) throws PushClientException, PushServerException {
        String apiKey = ConfigProperty.getKey("API_KEY_Android");
        String secretKey = ConfigProperty.getKey("SECRET_KEY_Android");
        PushKeyPair pair = new PushKeyPair(apiKey, secretKey);
        BaiduPushClient pushClient = new BaiduPushClient(pair, BaiduPushConstants.CHANNEL_REST_URL);
        pushClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                System.out.println(event.getMessage());
            }
        });

        try {
            PushMsgToTagRequest request = new PushMsgToTagRequest()
                    .addTagName("member")
                    .addMsgExpires(new Integer(3600))
                    .addMessageType(1)  
                    .addMessage(message)
                    .addDeviceType(3);
            PushMsgToTagResponse response = pushClient.pushMsgToTag(request);
            System.out.println("msgId: " + response.getMsgId() + ",sendTime: " + response.getSendTime() + ",timerId: "
                    + response.getTimerId());
        } catch (PushClientException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                e.printStackTrace();
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                System.out.println(String.format("requestId: %d, errorCode: %d, errorMessage: %s", e.getRequestId(),
                        e.getErrorCode(), e.getErrorMsg()));
            }
        }
    }

    public static void push2IOS(String title, String description,String pushKey) throws PushClientException, PushServerException {
        String apiKey = ConfigProperty.getKey("API_KEY_IOS");
        String secretKey = ConfigProperty.getKey("SECRET_KEY_IOS");
        PushKeyPair pair = new PushKeyPair(apiKey, secretKey);
        BaiduPushClient pushClient = new BaiduPushClient(pair, BaiduPushConstants.CHANNEL_REST_URL);
        pushClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                System.out.println(event.getMessage());
            }
        });

        try {
            JSONObject notification = new JSONObject();
            JSONObject jsonAPS = new JSONObject();
            jsonAPS.put("alert", "我是单推");
            jsonAPS.put("sound", "ttt"); // 设置通知铃声样式,例如"ttt",用户自定义。
            notification.put("aps", jsonAPS);
            notification.put("description", description);

            PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest()
                    .addChannelId(pushKey)
                    .addMsgExpires(new Integer(3600)). // 设置message的有效时间
                    addMessageType(1).// 1:通知,0:透传消息.默认为0 注:IOS只有通知.
                    addMessage(notification.toString()).addDeployStatus(2). // IOS,
                                                                            // DeployStatus
                                                                            // => 1: Developer
                                                                            // 2: Production.
                    addDeviceType(4);// deviceType => 3:android, 4:ios
            PushMsgToSingleDeviceResponse response = pushClient
                    .pushMsgToSingleDevice(request);
            System.out.println("msgId: " + response.getMsgId() + ",sendTime: "
                    + response.getSendTime());
        } catch (PushClientException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                e.printStackTrace();
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                System.out.println(String.format("requestId: %d, errorCode: %d, errorMessage: %s", e.getRequestId(),
                        e.getErrorCode(), e.getErrorMsg()));
            }
        }
    }
}
  1. 配置文件内容
#IM Push
API_KEY_Android=cPdUbtfnsplRsYBwR43oPv6Cg
SECRET_KEY_Android=2sqRWCM5H6D81wKbrldjwG0bRCn

API_KEY_IOS=Hwdftdos5wwgIzsdODjA4OcrHI
SECRET_KEY_IOS=8d1503fda5de183ecc35a576c0d311
  1. 获取配置文件工具类
package com.sun4j.app.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class ConfigProperty {
    private static final String URL = "config.properties";
    private static final Properties properties = new Properties();
    static {
        loadProperties();
    }

    public static void loadProperties() {
        InputStream is = null;
        Resource rs = new ClassPathResource(URL);
        try {
            is = rs.getInputStream();
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static String getKey(String key) {
        return properties.getProperty(key);
    }
}
  1. 测试结果
public static void main(String[] args) throws PushClientException, PushServerException {
        //Android
        JSONObject jsonMsg = new JSONObject();
        jsonMsg.put("title", "hello ");
        jsonMsg.put("description", "你好");
        //push2TagAndroid(jsonMsg.toJSONString(), "user");
        //单个推送
        //push2Android("项目推送","呵呵哒", "3465930645394868000");

        //IOS
        JSONObject iosMsg = new JSONObject();
        JSONObject aps = new JSONObject();
        aps.put("alert", "百度推送IOS内容");
        aps.put("sound", "ttt");
        aps.put("badge", 1);
        iosMsg.put("description", "IOSTag你好");
        iosMsg.put("aps", aps);
        System.out.println(iosMsg.toJSONString());

        //单个推送
        push2IOS("凡你好", "娃儿", "5734180441672125644");

        //push2TagIOS("你好Tag", "我是备注","user");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值