Hello I am trying to send a push message to my device using Java. But I\'am allready getting problems when establishing the ssl connection. Here is the code so far:
Here my working example:
private String token = "";
private String host = "gateway.sandbox.push.apple.com";
private int port = 2195;
private String payload = "{\"aps\":{\"alert\":\"Message from Java o_O\"}}";
public APNSender() {
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(getClass().getResourceAsStream("cert.p12"), "".toCharArray());
KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance("SunX509");
keyMgrFactory.init(keyStore, "".toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyMgrFactory.getKeyManagers(), null, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
String[] cipherSuites = sslSocket.getSupportedCipherSuites();
sslSocket.setEnabledCipherSuites(cipherSuites);
sslSocket.startHandshake();
char[] t = token.toCharArray();
byte[] b = Hex.decodeHex(t);
OutputStream outputstream = sslSocket.getOutputStream();
outputstream.write(0);
outputstream.write(0);
outputstream.write(32);
outputstream.write(b);
outputstream.write(0);
outputstream.write(payload.length());
outputstream.write(payload.getBytes());
outputstream.flush();
outputstream.close();
} catch (Exception exception) {
exception.printStackTrace();
}
}
What I'm still curious about is how to receive error codes. I tried it with
InputStream in = sslSocket.getInputStream();
[...]
but no success.
The Apple docs say that there is no answer send when no errors occured but on the other hand they list a status code for "No errors encountered".