華為推送之服務端簡單開發


 個人覺得華為推送官方文檔寫得太。。。。哈哈!完全符合復制拿來用就好,今天我也去復制一番。

1.獲取華為appSecretKey和appId

2.然后就是復制官網的代碼(是不是純copy),最后就最后了,就沒什么了
/*===================================華為推送=================================*/
/**
* 刷新token
*/
public static void refreshToken() throws Exception {
String msgBody = MessageFormat.format(
"grant_type=client_credentials&client_secret={0}&client_id={1}",
URLEncoder.encode(ConstantsUnit.huaweiAppSecretKey, "UTF-8"), ConstantsUnit.huaweiAppId);
String response = httpPost(tokenUrl, msgBody, 5000, 5000);
JSONObject obj = JSONObject.parseObject(response);
accessToken = obj.getString("access_token");
tokenExpiredTime = System.currentTimeMillis() + (obj.getLong("expires_in") - 5 * 60) * 1000;

}
/**
* 華為推送
*
* @param deviceTokens 從數據庫查出來的設備tokens
* @param title
* @param message
*/
public static boolean huaweiBatchPush(List<String> deviceTokens, String title, String message, Map<String,String> parm) {
log.info("華為設備:{}",deviceTokens);
try {
if (tokenExpiredTime <= System.currentTimeMillis()) {
refreshToken();
}
if (!CollectionUtils.isEmpty(deviceTokens)) {
JSONArray array = new JSONArray();
array.addAll(deviceTokens);

//僅通知欄消息需要設置標題和內容,透傳消息key和value為用戶自定義
JSONObject body = new JSONObject();
body.put("title", title);
body.put("content", message);
JSONObject param = new JSONObject();
//定義需要打開的appPkgName
param.put("appPkgName", ConstantsUnit.huaweiPackageName);
//param.put("intent","#Intent;compo=com.rvr/.Activity;S.W=U;end");
JSONObject action = new JSONObject();
//類型3為打開APP,其他行為請參考接口文檔設置,默認值
action.put("type", 3);
//消息點擊動作參數
action.put("param", param);
JSONObject msg = new JSONObject();
//3: 通知欄消息,異步透傳消息請根據接口文檔設置
msg.put("type", 3);
//消息點擊動作
msg.put("action", action);
//通知欄消息body內容示例代碼
msg.put("body", body);
List<Map<String,String>> cust = new ArrayList<>(1);
//cust.add(parm);
//華為PUSH消息總結構體
JSONObject hps = new JSONObject();
hps.put("msg", msg);
// 華為自定義消息推送 , ext中 customize必須為list模式
JSONObject ext = new JSONObject();
ext.put("biTag", "Trump");
//ext.put("customize", cust);
hps.put("ext", ext);
JSONObject payload = new JSONObject();
payload.put("hps", hps);

String postBody = MessageFormat.format(
"access_token={0}&nsp_svc={1}&nsp_ts={2}&device_token_list={3}&payload={4}",
URLEncoder.encode(accessToken, "UTF-8"),
URLEncoder.encode("openpush.message.api.send", "UTF-8"),
URLEncoder.encode(String.valueOf(System.currentTimeMillis() / 1000), "UTF-8"),
URLEncoder.encode(array.toString(), "UTF-8"),
URLEncoder.encode(payload.toString(), "UTF-8"));
String postUrl = apiUrl + "?nsp_ctx=" + URLEncoder.encode("{\"ver\":\"1\", \"appId\":\"" + ConstantsUnit.huaweiAppId + "\"}", "UTF-8");
//發送PUSH消息
String result = httpPost(postUrl, postBody, 5000, 5000);
log.debug("++++推送到華為結果為:{}",result);
if (StringUtils.isNotBlank(result)) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
log.error("華為推送失敗:", e);
}
return false;
}

public static String httpPost(String httpUrl, String data, int connectTimeout, int readTimeout) throws IOException {
OutputStream outPut = null;
HttpURLConnection urlConnection = null;
InputStream in = null;

try {
URL url = new URL(httpUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
urlConnection.setConnectTimeout(connectTimeout);
urlConnection.setReadTimeout(readTimeout);
urlConnection.connect();

// POST data
outPut = urlConnection.getOutputStream();
outPut.write(data.getBytes("UTF-8"));
outPut.flush();

// read response
if (urlConnection.getResponseCode() < 400) {
in = urlConnection.getInputStream();
} else {
in = urlConnection.getErrorStream();
}

List<String> lines = IOUtils.readLines(in, urlConnection.getContentEncoding());
StringBuffer strBuf = new StringBuffer();
for (String line : lines) {
strBuf.append(line);
}
return strBuf.toString();
} finally {
IOUtils.closeQuietly(outPut);
IOUtils.closeQuietly(in);
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM