ios推送 java做服务端
之前一篇文章介绍了ios推送,使用php做客客户端,这里介绍java实现服务端,证书的配置以及IOS客户端的代码这里就不赘述了,主要介绍服务端证书的生成和推送的代码,java需要的证书实现方式,直接导出就可以了
输入密码导出文件push.p12
java的实现代码为:
public static void main(String[] args) {
try {
String deviceToken = "xxxxxxx";
//被推送的iphone应用程序标示符
PayLoad payLoad = new PayLoad();
payLoad.addAlert("测试我的push消息");
payLoad.addBadge(1);
payLoad.addSound("default");
PushNotificationManager pushManager = PushNotificationManager.getInstance();
pushManager.addDevice("iphone", deviceToken);
String host="gateway.sandbox.push.apple.com"; //测试用的苹果推送服务器
int port = 2195;
String certificatePath = "D:/push.p12"; //刚才在mac系统下导出的证书
String certificatePassword= "123456";
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");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("push faild!");
return;
}
System.out.println("push succeed!");
}
需要用到的jar包
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
--------------------------------------------------------------
以上用到的是开源项目javapns的推送方式,还有另外一种方式
public static void main(String[] args) {
String keyPath = "/Users/allen/Desktop/push.p12";
String ksType = "PKCS12";
String ksPassword = "123456";
String ksAlgorithm = "SunX509";
String deviceToken = "cd265a77f1b4421e10902b2d3422d6b47bcdc0e96de836d89b86c6c2037a571d";
String serverHost = "gateway.sandbox.push.apple.com";
int serverPort = 2195;
try {
InputStream certInput = new FileInputStream(keyPath);
KeyStore keyStore = KeyStore.getInstance(ksType);
keyStore.load(certInput, ksPassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(ksAlgorithm);
kmf.init(keyStore, ksPassword.toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, null);
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
Socket socket = socketFactory.createSocket(serverHost, serverPort);
StringBuilder content = new StringBuilder();
String text = "this is a test.";
content.append("{\"aps\":");
content.append("{\"alert\":\"").append(text)
.append("\",\"badge\":1,\"sound\":\"")
.append("ping1").append("\"}");
content.append(",\"cpn\":{\"t0\":")
.append(System.currentTimeMillis()).append("}");
content.append("}");
byte[] msgByte = makebyte((byte)1, deviceToken, content.toString(), 10000001);
System.out.println(msgByte);
socket.getOutputStream().write(msgByte);
socket.getOutputStream().flush();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 组装apns规定的字节数组 使用增强型
*
* @param command
* @param deviceToken
* @param payload
* @return
* @throws IOException
*/
private static byte[] makebyte(byte command, String deviceToken, String payload, int identifer) {
byte[] deviceTokenb = decodeHex(deviceToken);
byte[] payloadBytes = null;
ByteArrayOutputStream boas = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(boas);
try {
payloadBytes = payload.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
try {
dos.writeByte(command);
dos.writeInt(identifer);//identifer
dos.writeInt(Integer.MAX_VALUE);
dos.writeShort(deviceTokenb.length);
dos.write(deviceTokenb);
dos.writeShort(payloadBytes.length);
dos.write(payloadBytes);
return boas.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private static final Pattern pattern = Pattern.compile("[ -]");
private static byte[] decodeHex(String deviceToken) {
String hex = pattern.matcher(deviceToken).replaceAll("");
byte[] bts = new byte[hex.length() / 2];
for (int i = 0; i < bts.length; i++) {
bts[i] = (byte) (charval(hex.charAt(2*i)) * 16 + charval(hex.charAt(2*i + 1)));
}
return bts;
}
private static int charval(char a) {
if ('0' <= a && a <= '9')
return (a - '0');
else if ('a' <= a && a <= 'f')
return (a - 'a') + 10;
else if ('A' <= a && a <= 'F')
return (a - 'A') + 10;
else{
throw new RuntimeException("Invalid hex character: " + a);
}
}