百度雲訊息推送(Java服務端開發)
註冊成為百度開發者
建立/配置應用(有Android 和 iOS 平臺)
1)獲取 ApiKey/SecretKey
ApiKey是應用標識,在SDK呼叫過程中唯一標識一個應用 SecretKey是呼叫API時的Token,用來驗證請求的合法性,請注意保密
2)ApiKey/SecretKey 在應用建立完畢後可以在應用詳情頁中查到
3)在服務端開發時需要對應的 ApiKey 和 SecretKey,需要在對應專案的配置檔案中進行配置,必須與上述配置中的保持一致整合 客戶端SDK , “雲推送”服務支援 Android平臺 及 iOS平臺
可以通過上述配置詳情中的二維碼下載pushDemo,進行一些簡單的測試(僅限Android,iOS沒有二維碼,詳細資訊參考使用 管理控制檯 或 服務端SDK 推送訊息
推送接受情況可以檢視 pushDemo 的日誌資訊服務端的開發(以便服務端SDK推送訊息)
參考文件
1)下載 Java服務端SDK:
Baidu-Push-Server-SDK-Java-3.0.1 .zip ()
目錄結構
2)匯入上述的 jar 包
3)編寫訊息推送的工具類
參考 sample 包下的例項 或者 文件中 Java SDK API
4)對寫好的每個工具方法進行測試
測試類中直接呼叫方法,模擬傳參, channelId 是唯一的在pushDemo 的日誌中可以拿到
測試結果可以在控制檯檢視或者在打包的APP(移動端打包,安裝在測試手機上)上可以測試看是否傳送成功部分工具類程式碼(自己編寫)
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");**
相關推薦
百度雲訊息推送(Java服務端開發)
註冊成為百度開發者 建立/配置應用(有Android 和 iOS 平臺) 1)獲取 ApiKey/SecretKey ApiKey是應用標識,在SDK呼叫過程中唯一標識一個應用 SecretKey是呼叫API時的Token,用來驗證請求的合法性,請注意保
百度雲訊息推送
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
iOS訊息推送(Java實現)
首先來了解一下蘋果的訊息推送APNS(英文全稱:Apple Push Notification service) 先來看兩張蘋果對於推送的兩張解釋圖: 大概的意思就是,提供商把訊息推送至蘋果的推送伺服器,再由蘋果推送伺服器將訊息推送給手機客戶端,或者反過來手機客戶端把
如何使用極光推送,java服務端向鐳射伺服器進行推送
第一種:使用官方的sdk直接使用 /** * <pre>專案名稱:bsa-admin-api * 檔名稱:Test.java * 包名:com.bsa.api.jiguang * 建立日期:2018年12月10日下午2:30:19 * Copyright (c
極光推送JPush java服務端程式碼
public void sendNotificationWirhAlias_Android(String title,String notification,String alias){ try { PushPayload payload = PushPayload
在瀏覽器進行大檔案分片上傳(java服務端實現)
最近在做web網盤的系統,網盤最基本的功能便是檔案上傳,但是檔案上傳當遇到大檔案的時候,在web端按傳統方式上傳簡直是災難,所以大檔案上傳可以採用分片上傳的辦法。其主要思路是:1.大檔案上傳時進行分片;2.分片上傳;3.對分片檔案進行合併。 思路比較清晰簡單,但一些問題在於:1.大檔案如何進
開始第一篇部落格——(JAVA後端開發)秋招之路
距離秋招還有短短的一個月時間,7月份中旬就會有大廠開始招聘,秋招會持續幾個月時間,一直到10月份,11月份。需要為其做好更多的準備,同時也要有好的心態,雖然還沒有實際的面試經驗,但是通過近期刷了的很多面經,還是從中學到很多。後期需要做好時間規劃,從各個方面去著手學習。寫在學習
【極光推送】jpush服務端開發詳盡過程
package com.weiwend.jdpush.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import jav
支付相關(一):APP支付寶支付(JAVA服務端開發)
開發環境:springboot最近一年兩個專案開發,其中APP支付這塊用到了微信支付,支付寶支付,以及轉賬到微信零錢,轉賬到支付寶賬號等功能,下面會分成4個文章來介紹。具體的開通微信和支付寶問題我不再敘述,直接上程式碼,程式碼會打包放在CSDN去下載,沒有分的可以找我。簽約注
Java後端實現安卓/IOS移動端訊息推送(百度雲推送)
本文主要介紹Java伺服器端如何藉助第三方推送平臺(百度雲推送)推送給移動端訊息。 使用案例介紹: 根據客戶的需求,需要做一個類似淘寶訊息推送的功能,客戶下訂單、訂單付款、訂單商品已發貨,以及客戶完成評論,都需要以訊息推送提示的方式告知商家和賣家這麼一個功能,由於之前沒有實現過這方面的功
3行java代碼實現百度站長主動推送12
收錄 工具 eboot ont 提交 pan 下載 工具類 百度收錄 介紹 當網站新增了一個網頁之後,此時這個網頁是不能夠立馬被百度收錄的,如果想以最快的速度被百度收錄則可以使用百度站長工具中的連接提交來主動向百度提交,讓百度收錄該網頁。 本文演示java使
小程式訊息推送(含原始碼)java實現小程式推送,springboot實現微信訊息推送
最近需要開發微信和小程式的推送功能,需要用java後臺實現推送,自己本身java和小程式都做,所以就自己動手實現下小程式的模版推送功能推送。 實現思路 1 小程式獲取使用者openid,收集formid傳給java後臺 2 java推送訊息給指定小程式使用
JAVA前後端實現WebSocket訊息推送(針對性推送)
1、需要新增依賴包,在pom.xml檔案中新增 javax javaee-api 7.0 provided 2、客戶端程式碼 在這裡我為了做成httpsession登入後是同一個,所以我做成兩個頁面,一個登入跳轉頁面,一個用於連結Web
MQTT+ActiveMQ實現訊息推送(伺服器端java實現)
上一篇文章已經介紹了mqtt+activemq實現訊息推送移動端的實現,也介紹了利用自帶的web console進行訊息釋出的方法。但是在具體的專案應用中,當我們將需要將該訊息推送模組嵌入到一個後臺管理系統當中,我們就需要在web端來訪問activeMQ來進行訊
訊息推送(一)Comet介紹
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!  
tuxera ntfs for mac(破解版)百度雲_網盤(啟用碼)免費版下載
tuxera ntfs for mac(破解版)百度雲_網盤(啟用碼)免費版下載安裝這款軟體可以很好地解決蘋果電腦使用NTFS驅動,使得Mac完美相容NTFS檔案系統。由於這款軟體的操作非常簡單,一般情況下只要將它安裝在Mac中便能解決問題,所以對於Mac來說它就如同一個外掛一般存在著。 Tuxera nt
Go websocket 做訊息推送(視訊彈幕的簡單實現原理)
server.go package main import ( "github.com/gorilla/websocket" "net/http" "socket/impl" "time" ) var ( upGrader = websocket.Upgr
訊息推送(華為)
關於「程序保活」的需求總是很多,以往的解決辦法也是層出不窮,但是隨著Android系統的更新,99%的方法已經無效 三方SDK喚醒(不現實) 系統白名單(不靠譜) 應用全家桶(不現實) 系統廣播喚醒(不可控) 兩個Service互相喚醒(涼了) 使用Timer
呼叫cordova相關外掛進行訊息推送(通知欄提醒、響鈴、震動)
原文: 呼叫cordova相關外掛進行訊息推送(通知欄提醒、響鈴、震動) 最近專案中需要對自己軟體的備忘錄進行訊息推送,從而提醒使用者。閒話就不多說了,將自己用到的外掛以及使用方法簡單分享一下,有什麼做的不好的地方或者好的建議歡迎隨時提出,謝謝! 一、本地訊息通知外掛,這裡使用cor
MQTT+ActiveMQ實現訊息推送(移動端)
這個小程式是我導師給我佈置的一個任務,網上教程不是很多,遇到的一些困難都是自己解決的,所以寫出來分享一下,有什麼問題大家可以留言,盡力幫大家解決。 來到解壓目錄下,進入bin目錄下的win64資料夾(如何是32位機器則進入win32),執行activemq