码迷,mamicode.com
首页 > 其他好文 > 详细

百度推送代码备份

时间:2015-12-17 16:16:47      阅读:922      评论:0      收藏:0      [点我收藏+]

标签:

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

百度推送代码备份

标签:

原文地址:http://blog.csdn.net/omsvip/article/details/50341493

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!