Firebase cloud messaging rest API spring

2020-01-27 07:38发布

问题:

I have to make a Rest API in Spring Java for a multi tier arch in which DAO, Controller, Service manager needs to be build for a Firebase Cloud Messaging (FCM) to send push notifications messages to android application, but I can not able configure a server in Java to send notifications to devices. How could I?

回答1:

Here is the way that you can achieve this:

Step 1: Create project on firebase and generate server key.

Step 2: Generate a json object for fcm server. Here message may contains data object and notification object. It must also have receiver fcm id. Sample json is like:

{
    "notification":
        {
            "notificationType":"Test",
        "title":"Title ",
        "body":"Here is body"
        },
    "data":
        {"notificationType":"Test",
        "title":"Title ",
        "body":"Here is body"
        },
        "to":"dlDQC5OPTbo:APA91bH8A6VuJ1Wl4TCOD1mKT0kcBr2bDZ-X8qdhpBfQNcXZWlFJuBMrQiKL3MGjdY6RbMNCw0NV1UmbU8eooe975vvRmqrvqJvliU54bsiT3pdvGIHypssf7r-4INt17db4KIqW0pbAkhSaIgl1eYjmzIOQxv2NwwwwXg"
}

Step 3 : Write a Rest caller service that will communicate with fcm server by following url:

https://fcm.googleapis.com/fcm/send

Here is the sample working code:

public class PushNotificationServiceImpl {
    private final String FIREBASE_API_URL = "https://fcm.googleapis.com/fcm/send";
    private final String FIREBASE_SERVER_KEY = "YOUR_SERVER_KEY";


    public void sendPushNotification(List<String> keys, String messageTitle, String message) {


        JSONObject msg = new JSONObject();

        msg.put("title", messageTitle);
        msg.put("body", message);
        msg.put("notificationType", "Test");

        keys.forEach(key -> {
            System.out.println("\nCalling fcm Server >>>>>>>");
            String response = callToFcmServer(msg, key);
            System.out.println("Got response from fcm Server : " + response + "\n\n");
        });

    }

    private String callToFcmServer(JSONObject message, String receiverFcmKey) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization", "key=" + FIREBASE_SERVER_KEY);
        httpHeaders.set("Content-Type", "application/json");

        JSONObject json = new JSONObject();

        json.put("data", message);
        json.put("notification", message);
        json.put("to", receiverFcmKey);

        System.out.println("Sending :" + json.toString());

        HttpEntity<String> httpEntity = new HttpEntity<>(json.toString(), httpHeaders);
        return restTemplate.postForObject(FIREBASE_API_URL, httpEntity, String.class);
    }
}

You have to just call sendPushNotification(List<String> receiverKeys, String messageTitle, String message) then receiver will get push message

Thanks :)



回答2:

@Autowire the FCM in your @Component class after configure your FCM account. tutorial