我正在查看webpush-java代码。
我尝试使用 CLI 工具发送通知
java -jar build/libs/web-push-3.1.0-all.jar send-notification, etc.. etc..
。但这会导致 HTTP/1.1 400 未经授权注册。 可能是什么原因造成的?
更新:我用新密钥和订阅重复了发送通知......这次我注意到进一步的错误诊断:-
SLF4J:无法加载类"org.slf4j.impl.StaticLoggerBinder"。 SLF4J:默认为无操作 (NOP) 记录器实现 SLF4J:有关更多详细信息,请参阅 http://www.slf4j.org/codes.html#StaticLoggerBinder。 HTTP/1.1 400 未经授权注册 [内容类型: text/html; charset=UTF-8, 日期: 星期五, 16 三月 2018 10:02:46 GMT, 到期: 星期五, 16 三月 2018 10:02:46 GMT, 缓存控制: private, max-age=0, X-内容类型-选项: nosniff, X-帧选项: SAMEORIGIN, X-XSS-PROTECTION: 1; mode=block, Server: GSE, Alt-Svc: hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="41,39,35", 接受范围:无, 变化:接受编码,传输编码:分块] [分块:假]
图书馆作者在这里。正如@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);
}
});
});
}