百度云消息推送(Java服务端开发) - Go语言中文社区

百度云消息推送(Java服务端开发)


  1. 注册成为百度开发者

  2. 创建/配置应用(有Android 和 iOS 平台)
    1)获取 ApiKey/SecretKey
    ApiKey是应用标识,在SDK调用过程中唯一标识一个应用 SecretKey是调用API时的Token,用来验证请求的合法性,请注意保密
    2)ApiKey/SecretKey 在应用创建完毕后可以在应用详情页中查到
    3)在服务端开发时需要对应的 ApiKey 和 SecretKey,需要在对应项目的配置文件中进行配置,必须与上述配置中的保持一致

  3. 集成 客户端SDK , “云推送”服务支持 Android平台 及 iOS平台
    可以通过上述配置详情中的二维码下载pushDemo,进行一些简单的测试(仅限Android,iOS没有二维码,详细信息参考 http://push.baidu.com/doc/guide/index),然后在百度云控制台发送推送消息,查看pushDemo的日志查看接受情况

  4. 使用 管理控制台 或 服务端SDK 推送消息
    推送接受情况可以查看 pushDemo 的日志信息

  5. 服务端的开发(以便服务端SDK推送消息)
    参考文档
    1)下载 Java服务端SDK:
    Baidu-Push-Server-SDK-Java-3.0.1 .zip ()
    目录结构
    这里写图片描述
    2)导入上述的 jar 包
    3)编写消息推送的工具类
    参考 sample 包下的实例 或者 文档中 Java SDK API
    4)对写好的每个工具方法进行测试
    测试类中直接调用方法,模拟传参, channelId 是唯一的在pushDemo 的日志中可以拿到
    测试结果可以在控制台查看或者在打包的APP(移动端打包,安装在测试手机上)上可以测试看是否发送成功

  6. 部分工具类代码(自己编写)

package utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.management.Query;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;

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.BaiduPush;
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.MsgSendInfo;
import com.baidu.yun.push.model.PushBatchUniMsgRequest;
import com.baidu.yun.push.model.PushBatchUniMsgResponse;
import com.baidu.yun.push.model.PushMsgToAllRequest;
import com.baidu.yun.push.model.PushMsgToAllResponse;
import com.baidu.yun.push.model.PushMsgToSingleDeviceRequest;
import com.baidu.yun.push.model.PushMsgToSingleDeviceResponse;
import com.baidu.yun.push.model.QueryMsgStatusRequest;
import com.baidu.yun.push.model.QueryMsgStatusResponse;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;

import constants.Constants;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import play.Logger;

/**
 * 新版本消息推送
 * @author Elsa
 *
 */
public class PushMessageNew {

    /**
     * 推送初始化
     * @return
     */
    private static BaiduPushClient initPushClient(){
        // 1. get apiKey and secretKey from developer console
        PushKeyPair pair = null;
        pair = new PushKeyPair("GxApW0TRv9aFqwGDB64oFkd2", "jhVWS2LdaU70MnY9OkSwA58Qdzn2tQOE");

        // 2. build a BaidupushClient object to access released interfaces
        BaiduPushClient pushClient = new BaiduPushClient(pair,"api.tuisong.baidu.com");

        // 3. register a YunLogHandler to get detail interacting information
        pushClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                System.out.println(event.getMessage());
            }
        });
        return  pushClient;
    }
    /**
     * Android 推送消息给批量设备(批量单播)IOS 不支持
     * @param title  通知标题
     * @param description 通知文本内容
     * @param channelIds  
     * @param deviceType
     * @return
     * @throws IOException 
     */
    public static Map<String, Object> androidPushBatchUniMsg(String title,String description,String[] channelIds,int deviceType) throws IOException{

        BaiduPushClient pushClient = initPushClient();
        Map<String, Object> jsonMap = new HashMap<String, Object>();

        try {
            // 4.specify request arguments
            //创建 Android 通知
            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);
            notification.put("url", "http://push.baidu.com"); 

            JSONObject jsonCustormCont = new JSONObject();
            jsonCustormCont.put("key", "value"); //自定义内容,key-value
            notification.put("custom_content", jsonCustormCont);

            PushBatchUniMsgRequest request = new PushBatchUniMsgRequest()
                    .addChannelIds(channelIds)
                    .addMsgExpires(new Integer(3600))
                    .addMessageType(1)
                    .addMessage(notification.toString())
                    .addDeviceType(deviceType)
                    .addTopicId("BaiduPush");// 设置类别主题
            // 5. http request
            PushBatchUniMsgResponse response = pushClient
                    .pushBatchUniMsg(request);
            // Http请求结果解析打印
            System.out.println(String.format("msgId: %s, sendTime: %d",
                    response.getMsgId(), response.getSendTime()));

            Logger.debug(String.format("msgId: %s, sendTime: %d",response.getMsgId(), response.getSendTime()));

            jsonMap.put("msgId", response.getMsgId());
            jsonMap.put("sendTime",response.getSendTime());

        } catch (PushClientException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                try {
                    throw e;
                } catch (PushClientException e1) {
                    e1.printStackTrace();
                }
            } else {
                e.printStackTrace();
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                try {
                    throw e;
                } catch (PushServerException e1) {
                    e1.printStackTrace();
                }
            } else {
                Logger.error(String.format(
                        "requestId: %d, errorCode: %d, errorMessage: %s",
                        e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            }
        }
        return jsonMap;
    }

    /**
     * 推送消息给所有设备,广播推送。
     * @param title
     * @param description
     * @param sendTime
     * @param expireTime
     * @param messageType
     * @param openType
     * @param url
     * @param deviceType
     * @return
     * @throws PushClientException
     * @throws PushServerException
     */
    public static Map<String, Object> pushMsgToAll(String title,String description,long sendTime,int expireTime,int messageType,int openType,
            String url,int deviceType,String alert,Object ...obj) throws PushClientException, PushServerException{
        BaiduPushClient pushClient = initPushClient();
        Map<String, Object> jsonMap = new HashMap<String,Object>();

        JSONObject message = new JSONObject();


        if(deviceType == 3){ // Android 设备
            message.put("title", title);
            message.put("description",description);
            message.put("notification_builder_id", 0);
            message.put("notification_basic_style", 4);
            message.put("open_type", openType); //默认 1
            message.put("url", url);

            JSONObject jsonCustormCont = new JSONObject();

            if(StringUtils.isNotBlank(obj.toString())){
                for (int i = 0; i < obj.length; i++) {
                    jsonCustormCont.put("key"+ (i+1), obj[i]); //自定义内容,key-value
                }
            }

            message.put("custom_content", jsonCustormCont);

        }else if(deviceType == 4){ //iOS 设备

            JSONObject jsonAPS = new JSONObject();
            jsonAPS.put("alert", alert);
            jsonAPS.put("sound", "ttt"); // 设置通知铃声样式,例如"ttt",用户自定义。
            message.put("aps", jsonAPS);

            if(StringUtils.isNotBlank(obj.toString())){
                for (int j = 0; j < obj.length; j++) {
                    message.put("key" + (j+1), obj[j]);
                }
            }
        }

        try {
            PushMsgToAllRequest request = new PushMsgToAllRequest()
                    .addMsgExpires(new Integer(expireTime)) //默认 new Integer(3600)
                    .addMessageType(messageType) // 0:透传消息  1:通知  默认是 0
                    .addMessage(message.toString())//添加透传消息
                    .addSendTime(sendTime) // 设置定时推送时间,必需超过当前时间一分钟,单位秒.实例2分钟后推送   System.currentTimeMillis() / 1000 + 120
                    .addDeviceType(deviceType);

            // 5. http request
            PushMsgToAllResponse response = pushClient.pushMsgToAll(request);

            // Http请求返回值解析
            Logger.debug(String.format("msgId: %s, sendTime: %d",response.getMsgId(), response.getSendTime()));

            jsonMap.put("msgId", response.getMsgId());
            jsonMap.put("sendTime",response.getSendTime());
            jsonMap.put("timerId", response.getTimerId()); //推送定时消息时,返回该字段,标识定时任务。

        } catch (PushClientException e) {
            //ERROROPTTYPE 用于设置异常的处理方式 -- 抛出异常和捕获异常,
            //'true' 表示抛出, 'false' 表示捕获。
            if (BaiduPushConstants.ERROROPTTYPE) { 
                throw e;
            } else {
                Logger.error("推送消息给所有设备出现异常 " + e.getMessage());
                e.printStackTrace();
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                Logger.error(String.format(
                        "requestId: %d, errorCode: %d, errorMsg: %s",
                        e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            }
        }
        return jsonMap;
    }

    /**
     * 向单个设备推送消息。
     * @param channelId
     * @param expireTime
     * @param messageType
     * @param title
     * @param description
     * @param openType
     * @param url
     * @param deviceType
     * @param obj
     * @return
     * @throws PushClientException
     * @throws PushServerException
     */
    public static Map<String, Object> pushMsgToSingleDevice(String channelId,int expireTime,int messageType,
            String title,String description,int openType,String url,
            int deviceType,String alert, Object ...obj) throws PushClientException, PushServerException{

        BaiduPushClient pushClient = initPushClient();
        Map<String, Object> jsonMap = new HashMap<String,Object>();

        JSONObject message = new JSONObject();


        if(deviceType == 3){ // Android 设备
            message.put("title", title);
            message.put("description",description);
            message.put("notification_builder_id", 0);
            message.put("notification_basic_style", 4);
            message.put("open_type", openType); //默认 1
            message.put("url", url);

            JSONObject jsonCustormCont = new JSONObject();

            if(StringUtils.isNotBlank(obj.toString())){
                for (int i = 0; i < obj.length; i++) {
                    jsonCustormCont.put("key"+ (i+1), obj[i]); //自定义内容,key-value
                }
            }

            message.put("custom_content", jsonCustormCont);

        }else if(deviceType == 4){ //iOS 设备

            JSONObject jsonAPS = new JSONObject();
            jsonAPS.put("alert", alert);
            jsonAPS.put("sound", "ttt"); // 设置通知铃声样式,例如"ttt",用户自定义。
            message.put("aps", jsonAPS);

            if(StringUtils.isNotBlank(obj.toString())){
                for (int j = 0; j < obj.length; j++) {
                    message.put("key" + (j+1), obj[j]);
                }
            }
        }


        try {
            PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest()
                    .addChannelId(channelId)
                    .addMsgExpires(expireTime) // message有效时间
                    .addMessageType(messageType)// 1:通知,0:透传消息. 默认为0 注:IOS只有通知.
                    .addMessage(message.toString())
                    .addDeviceType(deviceType);// deviceType => 3:android, 4:ios


            // 5. http request
            PushMsgToSingleDeviceResponse response = pushClient.pushMsgToSingleDevice(request);

            Logger.debug("msgId: " + response.getMsgId() + ",sendTime: "
                    + response.getSendTime());

            jsonMap.put("msgId", response.getMsgId());
            jsonMap.put("sendTime",response.getSendTime());

        }catch (PushClientException e) {
            //ERROROPTTYPE 用于设置异常的处理方式 -- 抛出异常和捕获异常,
            //'true' 表示抛出, 'false' 表示捕获。
            if (BaiduPushConstants.ERROROPTTYPE) { 
                throw e;
            } else {
                Logger.error("推送消息给所有设备出现异常 " + e.getMessage());
                e.printStackTrace();
            }
        } catch (PushServerException e) {
            if (BaiduPushConstants.ERROROPTTYPE) {
                throw e;
            } else {
                Logger.error(String.format(
                        "requestId: %d, errorCode: %d, errorMsg: %s",
                        e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
            }
        }
        return jsonMap;
    }


    /**
     * 查询消息推送状态,包括成功、失败、待发送、发送中4种状态。
     * @return
     * @throws PushClientException 
     * @throws PushServerException 
     */
    public static List<?> QueryMsgStatus(String[] msgIds,Integer deviceType) throws PushClientException, PushServerException{

        BaiduPushClient pushClient = initPushClient();
        //List<MsgSendInfo> sendInfo = null;

        QueryMsgStatusResponse response = null;
        try {
            // 4. specify request arguments
            QueryMsgStatusRequest request = new QueryMsgStatusRequest()
                    .addMsgIds(msgIds)
                    .addDeviceType(deviceType);

            // 5. http request
            response = pushClient.queryMsgStatus(request);

            // Http请求结果解析打印
            Logger.debug("totalNum: " + response.getTotalNum() + "n"
                    + "result:");
            /*
            将通知消息保存到日志中
            if( null != response){
                List<?> list = response.getMsgSendInfos();
                for (int i = 0; i < list.size(); i++) {
                    Object object = list.get(i);
                    if(object instanceof MsgSendInfo){
                        MsgSendInfo msgSendInfo = (MsgSendInfo) object;
                        StringBuilder strBuilder = new StringBuilder();
                        strBuilder.append("List[" + i + "]: {" + "msgId = "
                                + msgSendInfo.getMsgId() + ",status = "
                                + msgSendInfo.getMsgStatus() + ",sendTime = "
                                + msgSendInfo.getSendTime() + ",success = "
                                + msgSendInfo.getSuccessCount());
                        strBuilder.append("}n");
                        Logger.debug(strBuilder.toString());
                    }
                }
            }

            */
        } 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()));
            }
        }
        return response.getMsgSendInfos();
    }
}

测试代码

import java.io.IOException;
import java.util.List;
import java.util.Map;

import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;

import business.Bill;
import utils.PushMessageNew;

public class TestPush {

    public static void main(String[] args) throws PushClientException, PushServerException, IOException {

        /**
         * 单条推送
         Map<String, Object> resultMap = PushMessageNew.pushMsgToSingleDevice("3814863451180523498", 3600, 1, "代码测试", "测试ing", 2, "www.baidu.com", 4, "","");
         */

        /**
         * 批量推送
        String[] channelIds = {"4182697971366550372","3814863451180523498"} ;
        Map<String, Object> resultMap = PushMessageNew.androidPushBatchUniMsg("测试*****", "测试1205", channelIds , 3);
         */

        /**
         * 广播推送
        Map<String, Object> resultMap = PushMessageNew.pushMsgToAll("涌泉金服", "注册有礼", System.currentTimeMillis() / 1000 + 120, 3600, 1, 1, "https://www.baidu.com/", 3, "");
        System.out.println(resultMap);
         */

        /**
         * 消息状态的查看
         */
        String[] strs={"8361003517954776467"};
        List<?> list = PushMessageNew.QueryMsgStatus(strs, 3);
        System.out.println(list);
    }
}

7 . 遇到问题
推送返回errorCode: 30602, errorMessage: Request Params Not Valid,request header content_type charset should set to be UTF-8

原因
使用新版的rest API接口时,引用了1.1.2版本的jar包,导致UTF-8没有添加到content_type中。请确保1.1.2版本jar包在引用路径上与新版不产生冲突。
新的推送接口,即restAPI,会对content_type的属性进行判断,如果设置了UTF-8,则请求会接收,否则sdk抛异常。 java sdk1.1.2版本的content_type被设置为“application/x-www-form-urlencoded” ,没有添加UTF-8属性。

private void configureConnection(HttpURLConnection conn){
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    **conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");**
    conn.setRequestProperty("User-Agent","Yun/Java API Client(www.baidu.com)")
}

3.0.1版本设置了UTF-8,如图

**conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf8");**

其他常见问题

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/ITresource/article/details/53502463
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-09-13 13:03:13
  • 阅读 ( 1490 )
  • 分类:职场

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢