1. 程式人生 > >極光推送_總結_01_Java實現極光推送

極光推送_總結_01_Java實現極光推送

-type blank 經驗 內容 .cn util post org header

一、代碼實現

1.配置類—Env.java

技術分享圖片
package com.ray.jpush.config;

/**@desc  : 極光推送接入配置
 * 
 * @author: shirayner
 * @date  : 2017年9月27日 下午4:57:36
 */

public class Env {

    /**
     * 1.極光推送後臺APPKEY,MASTER_SECRET
     */
    public static final String APP_KEY = "354fb5c3dd4249ec11bc545d";
    
public static final String MASTER_SECRET = "8976605bf8a9ef9d8d97a8c2"; }
View Code

2.消息服務類—MessageService.java

技術分享圖片
package com.ray.jpush.service.message;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.ray.jpush.util.CommonUtil; import com.ray.jpush.util.HttpHelper; /**@desc : 極光推送消息服務 * * @author: shirayner * @date : 2017年11月29日 下午2:24:16 */ public class MessageService { private static final Logger log= LogManager.getLogger(MessageServiceTest.class
); //1.發送通知 private static final String SEND_NOTIFICATION_URL="https://api.jpush.cn/v3/push"; /** * @desc : 1.調用極光API * * @param url 接口url * @param registration_id 註冊id * @param alert 通知內容 * @param appKey * @param masterSecret * @return * JSONObject */ public static JSONObject sendNotification(String registration_id,String alert,String appKey,String masterSecret) { String base64_auth_string = CommonUtil.encryptBASE64(appKey + ":" + masterSecret); String authorization = "Basic " + base64_auth_string; String data=generateJson(registration_id,alert).toString(); log.debug("authorization:"+authorization); log.debug("data:"+data); return HttpHelper.doPost(SEND_NOTIFICATION_URL, data, authorization); } /** * @desc : 2.拼裝請求json * * @param registration_id 註冊id * @param alert 通知內容 * @return * JSONObject */ private static JSONObject generateJson(String registration_id,String alert){ JSONObject json = new JSONObject(); JSONArray platform = new JSONArray(); //1.推送平臺設置 platform.add("android"); platform.add("ios"); JSONObject audience = new JSONObject(); //2.推送設備指定,即推送目標 JSONArray registrationIdList = new JSONArray(); registrationIdList.add(registration_id); audience.put("registration_id", registrationIdList); JSONObject notification = new JSONObject(); //3.通知內容 JSONObject android = new JSONObject(); //3.1 android通知內容 android.put("alert", alert); //設置通知內容 android.put("builder_id", 1); JSONObject android_extras = new JSONObject();//android額外參數 android_extras.put("type", "infomation"); android.put("extras", android_extras); JSONObject ios = new JSONObject();//3.2 ios通知內容 ios.put("alert", alert); ios.put("sound", "default"); ios.put("badge", "+1"); JSONObject ios_extras = new JSONObject();//ios額外參數 ios_extras.put("type", "infomation"); ios.put("extras", ios_extras); notification.put("android", android); notification.put("ios", ios); json.put("platform", platform); json.put("audience", audience); json.put("notification", notification); return json; } }
View Code

3.HttpHelper工具類—HttpHelper.java

技術分享圖片
package com.ray.jpush.util;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * HTTP請求工具類
 */
public class HttpHelper {


    /**
     * @desc :1.發送POST請求-極光推送
     *  
     * @param url   接口url
     * @param data  請求包體
     * @param authorization  驗證字段,Authorization: Basic base64_auth_string
     *                       其中 base64_auth_string 的生成算法為:base64(appKey:masterSecret)
     *                       即,對 appKey 加上冒號,加上 masterSecret 拼裝起來的字符串,再做 base64 轉換。
     * @return
     * @throws Exception 
     *   JSONObject
     */
    public static JSONObject doPost(String url, String data ,String authorization) {
        //1.生成一個請求
        HttpPost httpPost = new HttpPost(url);

        //2.配置請求屬性
        //2.1 設置請求超時時間
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build();
        httpPost.setConfig(requestConfig);
        //2.2 設置數據傳輸格式-json
        httpPost.addHeader("Content-Type", "application/json");
        //2.3 設置Authorization
        httpPost.addHeader("Authorization", authorization.trim());
        
        //2.3 設置請求實體,封裝了請求參數
        StringEntity requestEntity = new StringEntity(data, "utf-8");
        httpPost.setEntity(requestEntity);

        //3.發起請求,獲取響應信息    
        //3.1 創建httpClient 
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            //3.3 發起請求,獲取響應
            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode()
                        + ", url=" + url);
                return null;
            }

            //獲取響應內容
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                System.out.println("POST請求結果:"+resultStr);

                //解析響應內容
                JSONObject result = JSON.parseObject(resultStr);

                //請求失敗
                if (result.getInteger("errcode")!=null && 0 != result.getInteger("errcode")) {  

                    System.out.println("request url=" + url + ",return value=");
                    System.out.println(resultStr);
                    int errCode = result.getInteger("errcode");
                    String errMsg = result.getString("errmsg");
                    
                    try {
                        throw new Exception("error code:"+errCode+", error message:"+errMsg);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } 
    
                    //請求成功
                } else {
                    return result;
                } 
                
            
            }
        } catch (IOException e) {
            System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();              //釋放資源

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

}
View Code

4.通用工具類—CommonUtil.java

技術分享圖片
package com.ray.jpush.util;

import sun.misc.BASE64Encoder;

/**@desc  : 
 * 
 * @author: shirayner
 * @date  : 2017年11月29日 下午3:11:33
 */
public class CommonUtil {


    /**
     * @desc :BASE64加密工具
     *  
     * @param str  待加密字符串
     * @return 
     *   String
     */
    public static String encryptBASE64(String str) {
        byte[] key = str.getBytes();
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String strs = base64Encoder.encodeBuffer(key);
        return strs;
    }
}
View Code

5.消息服務測試類—MessageServiceTest.java

技術分享圖片
package com.ray.jpush.service.message;

import org.junit.Test;

import com.ray.jpush.config.Env;

/**@desc  : 極光推送測試類
 * 
 * @author: shirayner
 * @date  : 2017年11月29日 下午3:54:42
 */
public class MessageServiceTest {

    /**
     * @desc :1.發送通知
     *   
     *   void
     */
    @Test
    public void testSendNotification() {
        String registration_id="121c83f760211fa5944";
        //String alert="hello,my honey!";
        String alert="您好:\\n 於巖軍在2017-11-15提出了一張金額為5的費用報銷單 BX10017110076 ,需要審批! \\n\\n\\n===================================================================\\n\\n秒針費用管理系統\\n\\n本郵件由系統自動發送,請勿回復。";
        String appKey=Env.APP_KEY;
        String masterSecret=Env.MASTER_SECRET;
        
        MessageService.sendNotification(registration_id, alert, appKey, masterSecret);
    }
}
View Code

二、參考資料

1.極光推送經驗之談-Java後臺服務器實現極光推送的兩種實現方式

極光推送_總結_01_Java實現極光推送