图书馆作者在这里。正如@collimarco 提到的,生成或编码密钥可能出了问题。您使用的是最新版本的库吗?您是如何生成密钥的?您是否将公钥复制到您的 Web 应用程序?
您可能还想看看spring-boot-web-push项目,我将 Web 推送库集成到一个干净的 Spring Boot 应用程序中。自述文件分五个步骤解释了如何运行应用程序,它应该只是工作 (™)。
具体来说,SendController.java展示了如何发送通知:
public class SendController {
private static final String PUBLIC_KEY = "BAPGG2IY3Vn48d_H8QNuVLRErkBI0L7oDOOCAMUBqYMTMTzukaIAuB5OOcmkdeRICcyQocEwD-oxVc81YXXZPRY";
private static final String PRIVATE_KEY = "A7xDGuxMZ4ufflcAhBW23xpoWZNOLwM4Rw2wXjP0y6M";
private static final String SUBJECT = "Foobarbaz";
private static final String PAYLOAD = "My fancy message";
@RequestMapping("/send")
public String send(@RequestParam("subscriptionJson") String subscriptionJson) {
Security.addProvider(new BouncyCastleProvider());
try {
PushService pushService = new PushService(PUBLIC_KEY, PRIVATE_KEY, SUBJECT);
Subscription subscription = new Gson().fromJson(subscriptionJson, Subscription.class);
Notification notification = new Notification(subscription, PAYLOAD);
HttpResponse httpResponse = pushService.send(notification);
int statusCode = httpResponse.getStatusLine().getStatusCode();
return String.valueOf(statusCode);
} catch (Exception e) {
return ExceptionUtils.getStackTrace(e);
}
}
}
push.js展示了如何注册订阅:
function subscribe() {
const publicKey = base64UrlToUint8Array('BAPGG2IY3Vn48d_H8QNuVLRErkBI0L7oDOOCAMUBqYMTMTzukaIAuB5OOcmkdeRICcyQocEwD-oxVc81YXXZPRY');
navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: publicKey
})
.then(function (subscription) {
return sendSubscriptionToServer(subscription);
})
.catch(function (e) {
if (Notification.permission === 'denied') {
console.warn('Permission for Notifications was denied');
} else {
console.error('Unable to subscribe to push.', e);
}
});
});
}