作者:MR张尉诚 | 来源:互联网 | 2023-09-05 19:42
我必须在SpringJava中创建一个RestAPI用于多层arch,其中需要为Firebase云消息传递(FCM)构建DAO,Controller,ServiceManager以
我必须在Spring Java中创建一个Rest API用于多层arch,其中需要为Firebase云消息传递(FCM)构建DAO,Controller,Service Manager以向Android应用程序发送推送通知消息,但我无法配置Java中的服务器,用于向设备发送通知.
我怎么能?
解决方法:
以下是您可以实现此目的的方法:
第1步:
在firebase上创建项目并生成服务器密钥.
第2步:
为fcm服务器生成json对象.这里的消息可能包含数据对象和通知对象.它还必须有接收器fcm id.样本json就像:
{
"notification":
{
"notificationType":"Test",
"title":"Title ",
"body":"Here is body"
},
"data":
{"notificationType":"Test",
"title":"Title ",
"body":"Here is body"
},
"to":"dlDQC5OPTbo:APA91bH8A6VuJ1Wl4TCOD1mKT0kcBr2bDZ-X8qdhpBfQNcXZWlFJuBMrQiKL3MGjdY6RbMNCw0NV1UmbU8eooe975vvRmqrvqJvliU54bsiT3pdvGIHypssf7r-4INt17db4KIqW0pbAkhSaIgl1eYjmzIOQxv2NwwwwXg"
}
第3步:
编写一个Rest调用者服务,它将通过以下url与fcm服务器通信:
https://fcm.googleapis.com/fcm/send
以下是示例工作代码:
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 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 httpEntity = new HttpEntity<>(json.toString(), httpHeaders);
return restTemplate.postForObject(FIREBASE_API_URL, httpEntity, String.class);
}
}
你必须只调用sendPushNotification(List receiverKeys,String messageTitle,String message)然后接收器将获得推送消息
谢谢 :)