japans的搭建(使用p12)

前情提要

由於公司服務器在使用apns服務的時候使用的是p12文件,經歷了p12生成步驟錯誤(正確步驟是在雙擊蘋果官網上下載的推送證書之後在鑰匙串中同時選中ssl證書和密匙導出p12)之後使用原先的神奇軟件Easy APNs Peovider無法檢測導出的p12是否正確。所以需要搭建一個直接使用p12的發送服務器,這裏使用到javapns.jar 2-2來搭建。

參考了網上相關教程和程序之後,使用java語言編寫的ApnsPush程序如下(log4j配置有些問題,這個部分可以跳過,估計是log4j.properties配置不正確)

import java.util.*;

import java.util.ArrayList;
import java.util.List;

import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
import javapns.notification.Payload;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.*;   
public class push {
    private static Log log = LogFactory.getLog(push.class.getName());
    private static   Logger logger1 = Logger.getLogger("console");   
     /************************************************
     測試推送服務器地址:gateway.sandbox.push.apple.com /2195 
     產品推送服務器地址:gateway.push.apple.com / 2195 

    需要javaPNS_2.2.jar包

     ***************************************************/
    /**

    *這是一個比較簡單的推送方法,

    * apple的推送方法

    * @param tokens   iphone手機獲取的token

    * @param path 這裏是一個.p12格式的文件路徑,需要去apple官網申請一個 

    * @param password  p12的密碼 此處注意導出的證書密碼不能爲空因爲空密碼會報錯

    * @param message 推送消息的內容

    * @param count 應用圖標上小紅圈上的數值

    * @param sendCount 單發還是羣發  true:單發 false:羣發

    */
    public void sendpush(List<String> tokens,String path, String password, String message,Integer count,boolean sendCount) {

        try {
            //message是一個json的字符串{“aps”:{“alert”:”iphone推送測試”}}

                PushNotificationPayload payLoad =  PushNotificationPayload.fromJSON(message);

                payLoad.addAlert("iphone推送測試"); // 消息內容

                payLoad.addBadge(count); // iphone應用圖標上小紅圈上的數值

                payLoad.addSound("default"); // 鈴音 默認



                PushNotificationManager pushManager = new PushNotificationManager();

                //true:表示的是產品發佈推送服務 false:表示的是產品測試推送服務

                pushManager.initializeConnection(new AppleNotificationServerBasicImpl(path, password, false));

                List<PushedNotification> notifications = new ArrayList<PushedNotification>(); 

                // 發送push消息

                if (sendCount) {

                log.debug("--------------------------apple 推送 單-------");

                Device device = new BasicDevice();

                device.setToken(tokens.get(0));

                PushedNotification notification = pushManager.sendNotification(device, payLoad, false);

                notifications.add(notification);

                } else {

                log.debug("--------------------------apple 推送 羣-------");

                List<Device> device = new ArrayList<Device>();

                for (String token : tokens) {

                device.add(new BasicDevice(token));

                }

                notifications = pushManager.sendNotifications(payLoad, device);

                }

                List<PushedNotification> failedNotifications = PushedNotification.findFailedNotifications(notifications);

                List<PushedNotification> successfulNotifications = PushedNotification.findSuccessfulNotifications(notifications);

                int failed = failedNotifications.size();

                int successful = successfulNotifications.size();



                if (successful > 0 && failed == 0) {

                log.debug("-----All notifications pushed 成功 (" + successfulNotifications.size() + "):");

                } else if (successful == 0 && failed > 0) {

                log.debug("-----All notifications 失敗 (" + failedNotifications.size() + "):");
                logger1.debug("-----All notifications 失敗 (" + failedNotifications.size() + "):");

                } else if (successful == 0 && failed == 0) {

                System.out.println("No notifications could be sent, probably because of a critical error");

                } else {

                log.debug("------Some notifications 失敗 (" + failedNotifications.size() + "):");
                logger1.debug("------Some notifications 失敗 (" + failedNotifications.size() + "):");
                log.debug("------Others 成功 (" + successfulNotifications.size() + "):");

                }

        // pushManager.stopConnection();

        } catch (Exception e) {

        e.printStackTrace();

        }

    }
    /**
     * TODO
     * @param args
     */
    public static void main(String[] args) {
           PropertyConfigurator.configure("/Users/zjx/Documents/workspace/ApnsPush/src/log4j.properties");   
           //在後臺輸出   
           Logger logger1 = Logger.getLogger("console");   
           logger1.debug("debug!!!");   
           logger1.info("info!!!");   
           logger1.warn("warn!!!");   
           logger1.error("error!!!");   
           logger1.fatal("fatal!!!"); 
        push send=new push();
        List<String> tokens=new ArrayList<String>();
        tokens.add("4447a26b6b5fbf7e4d7900b42e29a7efd243178aa47c2d55fe787634c6a0a5ca");
        String path="/Users/zjx/Desktop/證書dev.p12";
        String password="**";
        String message="{'aps':{'alert':'iphone推送測試'}}";
        Integer count=1;
        boolean sendCount=false;
        send.sendpush(tokens, path, password, message, count, sendCount);

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章