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

 我的以爲華爲推送官方文檔寫得太。。。。哈哈!徹底符合複製拿來用就好,今天我也去複製一番。數據庫

1.獲取華爲appSecretKey和appIdapi

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();        }    }}
相關文章
相關標籤/搜索