zoukankan      html  css  js  c++  java
  • 华为推送之服务端简单开发

     个人觉得华为推送官方文档写得太。。。。哈哈!完全符合复制拿来用就好,今天我也去复制一番。

    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();
    }
    }
    }
  • 相关阅读:
    Java中的HashMap
    单机百万连接调优和Netty应用级别调优
    简单排序(冒泡排序,插入排序,选择排序)
    使用AC自动机解决文章匹配多个候选词问题
    树状数组解决数组单点更新后快速查询区间和的问题
    LeetCode 763. Partition Labels
    LeetCode 435. Non-overlapping Intervals
    线段树
    无序数组求第K大的数
    KMP算法解决字符串匹配问题
  • 原文地址:https://www.cnblogs.com/xiaokangk/p/11101203.html
Copyright © 2011-2022 走看看