今天很顺利的弄了一个java push iphone的小程序,拿出来和大家分享一下吧。
前期准备工作:
?
??? 1. p12文件
??? 2. 在生成p12文件时所需要的密码
??? 3. 测试机器的tonken码
??? 4. 需要以下类库,bcprov-jdk16-145-1.jar?
???????????????????????????? commons-io-2.0.1.jar??
???????????????????????????? commons-lang-2.5.jar??
???????????????????????????? javapns-jdk16-163.jar
???????????????????????????? log4j-1.2.16.jar
?
?
准备工作已经做好,下面就是主要的java代码部分了:
? try {
???????????? String deviceToken = "98ea484fa 4fe8871a eb8e558d 0d443ee4 a89fb3bd 27d07c13 9e5e36a0 d2b726ad";//iphone手机获取的token
????????????? PayLoad payLoad = new PayLoad();
????????????? payLoad.addAlert("我的push测试");//push的内容
????????????? payLoad.addBadge(1);//图标小红圈的数值
????????????? payLoad.addSound("default");//铃音
???????????????????????
????????????? PushNotificationManager pushManager = PushNotificationManager.getInstance();
????????????? pushManager.addDevice("iPhone",deviceToken);
????????????? //Connect to APNs
????????????? //************************************************
????????????? //测试的服务器地址:gateway.sandbox.push.apple.com /端口2195
????????????? //????????????????????? 产品推送服务器地址:gateway.push.apple.com / 2195
????????????? //***************************************************/
????????????? String host= "gateway.sandbox.push.apple.com";
????????????? int port = 2195;
????????????? String certificatePath= "F:\\iphone.p12";//导出的证书
????????????? String certificatePassword= "iphone";//此处注意导出的证书密码不能为空因为空密码会报错
????????????? pushManager.initializeConnection(host, port,
certificatePath, certificatePassword,
SSLConnectionHelper.KEYSTORE_TYPE_PKCS12);
???????????????????????
????????????? //Send Push
????????????? Device client = pushManager.getDevice("iPhone");
????????????? pushManager.sendNotification(client, payLoad);
????????????? pushManager.stopConnection();
????????????? pushManager.removeDevice("iPhone");
????????????? System.out.println("OK");
???????????? }
???????????? catch (Exception e) {
?????????????????? e.printStackTrace();
???????????? }
?
如果测试成功会在控制台打印出"OK"
?
?
有一个做好的例子,我也拿出来了,请查看附件。