苹果的消息推送接口被开发人员诟病许久,终于推出了http2接口,payload的大小从255增加到了4k,协议也从binary改成了http,花了一天的时间,测试新的推送,也踩了不少坑,网上的资料也是残缺不全,在此记录一下。
https://github.com/CleverTap/apns-http2下载源码编译。
使用苹果证书,采用异步模式,官方示例如下。
FileInputStream cert = new FileInputStream("/path/to/certificate.p12");
final ApnsClient client = new ApnsClientBuilder()
.withProductionGateway()
.inAsynchronousMode()
.withCertificate(cert)
.withPassword("")
.withDefaultTopic("<your app's topic>")
.build();
Notification n = new Notification.Builder("<the device token>")
.alertBody("Hello").build();
client.push(n, new NotificationResponseListener() {
@Override
public void onSuccess(Notification notification) {
System.out.println("success!");
}
@Override
public void onFailure(Notification notification, NotificationResponse nr) {
System.out.println("failure: " + nr);
}
});
遇到的常见错误:
1.NotificationResponse{error=null, httpStatusCode=-1, responseBody='null', cause=javax.NET.ssl.SSLHandshakeException: Received fatal alert: handshake_failure}
升级JDK到1.8
2.NotificationResponse{error=null, httpStatusCode=-1, responseBody='null', cause=Java.io.IOException: unexpected end of stream on okhttp3.Address@74be3a63}
缺少jar包,仔细阅读apns-http2的Readme文档,发现其中一行:
Ensure that you have Jetty's ALPN JAR (OkHttp requires it) in your boot classpath
https://github.com/jetty-project/jetty-alpn/
下载编译,加入 bootclasspath
3.NotificationResponse{error=BadRequest, httpStatusCode=400, responseBody='{"reason":"TopicDisallowed"}', cause=null}
topic设置为:appid
至此,apns的推送终于成功了,payload有了质的飞跃,但是同时推送速度比之前慢了不少。需要有VPN或者VPS来翻墙加速。