Refactored and improved version of WebPush
- Switch from Gradle to Maven
- Updated dependencies
- OkHttp instead of httpcomponents
- Reduced code, cleanups and refactorings
- Fluent API
- Requires Java 21
- Add the WebPush4J dependency to your pom.xml:
<dependency>
<groupId>de.svenkubiak</groupId>
<artifactId>webpush4j</artifactId>
<version>x.x.x</version>
</dependency>
- Create a Subscriber or load from e.g. database
String json = ... //Json from initial subscription
Subscriber subscriber = Subscriber.from(json);
- Create a notification
Notification notification = Notification.create()
.withTitle("Hello!!")
.withBody("New Message from your favorite Server.");
- Send the notification to the subscriber
try {
WebPush.crerate()
.withPublicKey("PUBLIC KEY") //Vapid public key
.withPrivateKey("PRIVATE KEY") //Vapid private key
.withSubject("SUBJECT");
.withSubscriber(subscriber)
.withNotification(notification)
.send();
} catch (WebPushException e) {
e.printStackTrace();
}
import de.svenkubiak.webpush4j.Notification;
import de.svenkubiak.webpush4j.Subscriber;
import de.svenkubiak.webpush4j.WebPush;
import de.svenkubiak.webpush4j.exceptions.WebPushException;
public class Main {
public static void main(String... args) {
Subscriber subscriber = Subscriber.from(json);
Notification notification = Notification.create()
.withTitle("Hello!!")
.withBody("New Message from your favorite Server.");
try {
WebPush.crerate()
.withPublicKey("PUBLIC KEY") //Vapid public key
.withPrivateKey("PRIVATE KEY") //Vapid private key
.withSubject("SUBJECT");
.withSubscriber(subscriber)
.withNotification(notification)
.send();
} catch (WebPushException e) {
e.printStackTrace();
}
}
}