My requirement is that i am doing a news portal project where i want to send latest added news to all the tokens which i have. The issue i am facing is that, i am not able to use sendMulticast function in fire base, I am able to send notification for one single token with the content. But when I try to send notification for multiple tokens there are issues. I have used the needed dependencies like, guava, firebase admin and all. I have taken the code from firebase console itself.
The error i got is:
Error Sending Notifications: Unexpected HTTP response with status: 404
404. That’s an error.
The requested URL /batch
was not found on this server. That’s all we know.
Below is the code:
public class FireBaseMessagingService {
private static final Logger log = LoggerFactory.getLogger(FireBaseMessagingService.class);
@Autowired
FirebaseMessaging firebaseMessaging;
public String sendNotifications(NotificationMessagingFCM notifications) {
String title = notifications.getTitle();
String body = notifications.getBody();
String image = notifications.getImage();
List<String> recipientTokens = notifications.getRecipientToken();
Notification notification = Notification.builder().setTitle(title).setBody(body).setImage(image).build();
int batchSize = 500;
int totalSuccess = 0;
int totalFailure = 0;
for (int i = 0; i < recipientTokens.size(); i += batchSize) {
List<String> batchTokens = recipientTokens.subList(i, Math.min(i + batchSize, recipientTokens.size()));
MulticastMessage message = MulticastMessage.builder()
.addAllTokens(batchTokens)
.setNotification(notification)
.build();
try {
BatchResponse response = firebaseMessaging.sendMulticast(message);
totalSuccess += response.getSuccessCount();
totalFailure += response.getFailureCount();
if (response.getFailureCount() > 0) {
List<SendResponse> failures = response.getResponses();
for (int j = 0; j < failures.size(); j++) {
if (!failures.get(j).isSuccessful()) {
log.error("Failed to send notification to token: " + batchTokens.get(j) + " - "
+ failures.get(j).getException());
}
}
}
} catch (FirebaseMessagingException e) {
log.error("Error sending notifications: " + e.getMessage(), e);
return "Error Sending Notifications: " + e.getMessage();
}
}
return "Success: " + totalSuccess + " messages were sent, Failures: " + totalFailure;
}
}