如何在React Native中发起APNS的HTTP2请求?
在React Native中实现APNS VoIP推送(对应终端curl请求)
原始终端curl请求
curl -v \ -d '{"aps":{"alert":"Test","badge":42,"uuid":"testuuid"}, "data": {"Username": "Alex", "ConnectionId": "Alex123","uuid":"testuuid"},"uuid":"testuuid"}' \ -H "apns-push-type: voip" \ -H "apns-priority: 10" \ --http2 \ --cert voip.pem \ https://api.development.push.apple.com/3/device/c91119f600ccea97348b479e9648b3e29d12fae018a92da82bea6c18bba
核心限制说明
React Native自带的fetch和常用的axios都不支持HTTP2协议,也无法直接传入客户端SSL证书(.pem文件)——因为JS运行时没有权限操作原生的SSL证书配置,所以不能直接用这两个工具实现需求。
可行实现方案
1. 封装原生模块(推荐,稳定性最高)
分别在iOS和Android端实现APNS推送的HTTP2请求逻辑,再暴露给JS层调用:
- iOS端:使用原生
NSURLSession(天然支持HTTP2),加载.p12格式的证书(需先把.pem转成.p12),构造请求发送到APNS服务器。
示例Objective-C代码片段:NSURL *apnsUrl = [NSURL URLWithString:@"https://api.development.push.apple.com/3/device/c91119f600ccea97348b479e9648b3e29d12fae018a92da82bea6c18bba"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:apnsUrl]; request.HTTPMethod = @"POST"; // 设置APNS请求头 [request setValue:@"voip" forHTTPHeaderField:@"apns-push-type"]; [request setValue:@"10" forHTTPHeaderField:@"apns-priority"]; // 加载p12证书(需将证书放入iOS项目的Resources目录) NSString *certPath = [[NSBundle mainBundle] pathForResource:@"voip" ofType:@"p12"]; NSData *certData = [NSData dataWithContentsOfFile:certPath]; NSDictionary *options = @{(__bridge id)kSecImportExportPassphrase: @"你的证书密码"}; CFArrayRef items = NULL; OSStatus status = SecPKCS12Import((__bridge CFDataRef)certData, (__bridge CFDictionaryRef)options, &items); if (status == errSecSuccess && CFArrayGetCount(items) > 0) { NSDictionary *identityDict = CFArrayGetValueAtIndex(items, 0); SecIdentityRef identity = (__bridge SecIdentityRef)identityDict[(__bridge id)kSecImportItemIdentity]; // 配置URLSession的SSL证书 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; // 后续发送请求、处理响应... } - Android端:如果需要在Android设备上发起APNS请求,可使用
OkHttp(支持HTTP2)加载.pem证书,构造请求发送。
JS层通过NativeModules调用原生暴露的方法,传入推送payload即可。
2. 使用支持证书的第三方HTTP2库
可以尝试react-native-http2-client这类专门支持HTTP2的第三方库,注意以下要点:
- 将
.pem证书放入项目的原生资源目录(iOS的Resources、Android的assets)。 - 初始化请求时,指定证书路径、开启HTTP2协议,同时设置
apns-push-type、apns-priority等请求头,传入对应的JSON payload。
关键前置步骤
- 证书格式转换:iOS端需要把
.pem证书转成.p12格式,可通过openssl命令完成:openssl pkcs12 -export -out voip.p12 -inkey voip.key -in voip.crt - 权限配置:iOS项目需开启
Push Notifications和VoIP Services权限;Android项目需添加网络访问权限。
内容的提问来源于stack exchange,提问作者ShelbyIB
相关产品推荐
相关产品推荐

