How to send Firebase push notification to your Android or iOS client from application server example.
I will give you an example of How to send firebase push notification to Android or iOS devices from PHP, Java, C# or using Rest Client.
Here is Rest API example which we will use to send notifications to our client application. You can implement this Rest API in your application server.
HTTP METHOD : POST
URL: https://fcm.googleapis.com/fcm/send
Header :
Content-Type: application/json
Authorization: Server Key
(e.g key=AIzaSyD_Vw3Zf8XXXSDMSDKLMGyqR_Kyw5o)
You can find Servery key under Settings >Cloud messaging > Server key
Body :
You can send two types of data in request body.
1. Notification payload. (if you send notification using firebase console. It also sends notification payload.
Firebase SDK at client side do not handle or receive a push notification from the server.
Instead, Notification is passed to the Android OS for displaying in the notification panel.)
2. Data payload. (If you want to handle notification in your client application you should send data payload)
You can read about the difference in notification payload and data payload from this tutorial.
We will send data payload as Notification data payload.
Body:
{ “data”: { “title”: “Firebase notification”, “detail”: “I am firebase notification. you can customise me. enjoy”, }, “to” : “efaOvIXDbik:APA91bEkNUVWNaoA….” }
to = your application firebase token.
where to get this firebase token?
In Android Apps which handles firebase push notification.
•On Initial startup of the Project / Application, Firebase SDK will generate a unique device token inside method onTokenRefreshed.
override onTokenRefreshed(String token) { // from here you can save application token in your app server. }
will be called whenever a token is updated or generated.
And you have to save this token in your application server.
Above example is to send notification to single device.
Here is a rest client screenshot for more clarification.

How to Send push notification to all users or multiple devices from server side?
We already discussed how to send a push notification to the single device.
There are 2 ways of sending push notification to all devices or users from your app server using FCM.
- Using all firebase token’s and put them in registration_ids array.
You have to pass firebase registration tokens in registration_ids Array.
{ "registration_ids": [ "eQX_V2DoMDU:APA91bED-PobAzyYrWP4I3VSLcL7-o1-RhaOk3L9gE", "didwBCYh30E:APA91bh72X" ], "priority": "high", "data": { "title": "Firebase Notification Example", "detail": "This firebase push notification will be sent to all firebase tokens (devices) registered with your app server." } }
2. Topics
Now the second method is Topics.
- Topics are just keys which users subscribe to. Users have to subscribe to any topic.
- Users can subscribe to any existing topic or can create a new topic and than subscribe to it.
To subscribe to any topic. users/client use this code (this is Android Code)
FirebaseMessaging.getInstance().subscribeToTopic("anytopic");
HTTP POST REQUEST SAMPLE for send firebase push notification to all users who subscribed to news topic.
URL: https://gcm-http.googleapis.com/gcm/send HEADER: Content-Type:application/json Authorization:key=AIswgdyZ-4f...0HPYzPDSKNSSaA Body : { "to": "/topics/news", "data": { "message": "This is a FCM Topic Message!", }
You can implement this code in your application server.
Now all users/ devices who subscribed to topic “news” topic will receive a push notification.
Now we will write Java client code which will send Firebase (FCM) Push Notification and you can use this code example in your application server.
Firebase Cloud Messaging (FCM) JAVA SERVER SIDE CODE EXAMPLE
Step 1-
First of all, create a new project in your IDE (I used IntelliJ IDEA).
Step 2- Setup Gradle dependencies
Add below dependencies in your project.
- Javax Annotation
- Google Gson
- Apache HttpClient
group 'pushnotification' version '1.0-SNAPSHOT' apply plugin: 'java' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' compile 'javax.annotation:javax.annotation-api:1.2' compile 'com.google.code.gson:gson:2.8.1' compile 'org.apache.httpcomponents:httpclient:4.5.4' }
Step 3- Create Model / POJO classes for FCM Notification Data payload
import javax.annotation.Generated; import com.google.gson.annotations.SerializedName; @Generated("net.hexar.json2pojo") @SuppressWarnings("unused") public class NotificationData { @SerializedName("detail") private String mDetail; @SerializedName("title") private String mTitle; public String getDetail() { return mDetail; } public void setDetail(String detail) { mDetail = detail; } public String getTitle() { return mTitle; } public void setTitle(String title) { mTitle = title; } }
And
import javax.annotation.Generated; import com.google.gson.annotations.SerializedName; @Generated("net.hexar.json2pojo") @SuppressWarnings("unused") public class NotificationRequestModel { @SerializedName("data") private NotificationData mData; @SerializedName("to") private String mTo; public NotificationData getData() { return mData; } public void setData(NotificationData data) { mData = data; } public String getTo() { return mTo; } public void setTo(String to) { mTo = to; } }
Step 4- Sending Firebase Push Notifications API using Java Http Client
Create a new Application Class inside the main package of your project.
import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import model.NotificationData; import model.NotificationRequestModel; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.lang.reflect.Type; public class ApplicationClass { public static void main(String[] args) throws IOException { System.out.println("Welcome to Developine"); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost( "https://fcm.googleapis.com/fcm/send"); // we already created this model class. // we will convert this model class to json object using google gson library. NotificationRequestModel notificationRequestModel = new NotificationRequestModel(); NotificationData notificationData = new NotificationData(); notificationData.setDetail("this is firebase push notification from java client (server)"); notificationData.setTitle("Hello Firebase Push Notification"); notificationRequestModel.setData(notificationData); notificationRequestModel.setTo("eHp6V2Wtr4I:APA91bFLHRuScumQB0lnNRmeirxu5kV2lUPDZ8SbZKz"); Gson gson = new Gson(); Type type = new TypeToken<NotificationRequestModel>() { }.getType(); String json = gson.toJson(notificationRequestModel, type); StringEntity input = new StringEntity(json); input.setContentType("application/json"); // server key of your firebase project goes here in header field. // You can get it from firebase console. postRequest.addHeader("Authorization", "key=AAAA7-UgB34:APA91bFhpZ1-MYyFfQd2gof0vUAFKNcQCmmf_10acMn-HS_0iBBvP"); postRequest.setEntity(input); System.out.println("reques:" + json); HttpResponse response = httpClient.execute(postRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } else if (response.getStatusLine().getStatusCode() == 200) { System.out.println("response:" + EntityUtils.toString(response.getEntity())); } } }
Simply Run this code and it will send Firebase Push Notification to your Android/iOS application using Firebase Server.
This will be the output of above Java code.
Welcome to Developine request:{"data":{"detail":"this is firebase push notification from java client (server)","title":"Hello Firebase Push Notification"},"to":"eHp6V2Wtr4I:APA91b4tPNStf-vFTGNy8RSbZKz"} response:{"multicast_id":6045444993562588493,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1515057939997633%6e39fd7ecd"}]}
I copied token of a single user manually and used in above code.
In a real-world project, you have to send Firebase token which is generated on the client side (Mobile App) to your application server.
Conclusion:-
We first learned how we can send Firebase push notification using Rest Client.
We also learned how to send Firebase Push Notification from java client using firebase server.
Recommended Reading:-
How to setup firebase push notification in Android
If this helped you share this article and subscribe to our website for latest updates on Kotlin, Android, Spring Boot.
how to pass data like employee id and name in data.?
{ “data”:
{
“title”: “Firebase notification”,
“detail”: “I am firebase notification. you can customise me. enjoy”,
“emp_id”:”100″,
“emp_name”:”someone”
},
“to” : “efaOvIXDbik:APA91bEkNUVWNaoA….”
}
Hi Mano sorry for late reply. you are doing it in the right way.
data payload will be received by your application and you have to parse it as json.
where ı place this code in android ?FirebaseMessaging.getInstance().subscribeToTopic(“anytopic”);
You can place this code inside onCreate of Application class or your MainActivity.
notificationRequestModel.setTo(“eHp6V2Wtr4I:APA91bFLHRuScumQB0lnNRmeirxu5kV2lUPDZ8SbZKz”);
setTo ? what…
Can you please tell me what is the eHp6V2Wtr4I:APA91bFLHRuScumQB0lnNRmeirxu5kV2lUPDZ8SbZKz
Thank you
it is the value of firebase token. which firebase SDK generates for identifying each device uniquely.
Hi ,
Are we using “Authorization:key=AIswgdyZ-4f…0HPYzPDSKNSSaA” for the authentication purpose? or any other authentication option we can use in rest call?
Please carify below mentioned point:
•On Initial startup of project Firebase SDK will generate a unique device token. override method onTokenRefreshed() will be called whenever a token is updated or generated. is it mandatory?
Yes each project at firebase has unique authorization key.
you need this authorization key when you have to send firebase push notification from application server to your Android or iOS app.
Clarification:
this is code snippet from firebase android client.
firebase sdk generate a token for each device which register itself for handling and receving firebase push notifications.
this token is used to send firebase push notification to single device from firebase console or from firebase app server.
thanks a lot for that useful topic,,,
Code run successfully and the result was
response:{“multicast_id”:9063856595900126638,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1537959412320992%56437df3f9fd7ecd”}]}
— i checked the Token-id
and the server key in >>> Project Settings >>> Cloud Messaging >>> copied the Server Key Token
but no notification was delivered on my android app 🙁
Hi, Just to make sure you sent notification to your android app using notification payload or data payload ?
and your android app was in foreground or background ?
i did as the above code of the ApplicationClass ,,, i tested the Token from the Firebase API on the console “console.firebase.google.com” and i could recieve the notification on my android while the APP is in forground or background
but using the Code and the Server the reply is
reques:{“data”:{“detail”:”this is firebase push notification from java client (server)”,”title”:”Hello Firebase Push Notification”},”to”:”c_qmaestHZc:APA91bHaWCVmu4e13vzkk4Lj6v0_VCAL7lybvabM8S4jRRfrkOlhd3dZKHKsMNCWJ3TR-7EYi_srMs8C89OO9yNCRt1bEYD-coJncLhF70wskpgFYzC_8Uv0wdhKYJrXdV7mKMTWvE”}
response:{“multicast_id”:9162091118037246220,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1538292617254410%56437df3f9fd7ecd”}]}
for Authentication i used the Server key in Project Settings >>> Cloud Messaging >>> Project credentials >>> then copied the Value of Server Key
AAAA-sqmtME:APA91bGzOo5zsRQVpFvooXQAhvuTJY3K9AQky1OlziQkxWz7lqcvehzLP8wnsCNZmGVAIRHsAxs6GhBnkLfiLXEQq__ABRof4CzFdIzY4x8lVhADLVdMMbGObUIDd_Lsml4Q_rOaOnoktZcFdwMp4MpLdAQ
and why the notification is received from the Console and Not Received from the Code ? 🙁
thanks in advance
If you send notification from firebase console it will always be “Notification Payload”.
and using code in ApplicationClass you are sending data payload.
Make sure to check your Android app logs. You have received notification actually in onMessageReceived() function.
But you have to parse its json and display it using local notification manager class, means Firebase SDK will not send notification to Android OS for displaying, you have to do it yourself.
I hope your concepts will be clear now. 🙂
Hello sir i integrated your source code,also get response but when i send notificatin through one devise it will not received by other devices.i have also integrate recieved notification code.in same app.
Hi Santosh,
I am sorry I am unable to understand your query. what does this mean notification sent through one device is not received on other devices.
You are trying to send a push notification to a single device using my code? or you want to send notification to multiple devices?
Hi Team,
We are facing issue while sending push notification to ISO Device. IPhone 7 with IOS 12X version.
It was working absolutly fine till few days back. now its not working and we are getting success response.
Do let us know if any change is required to do so.
Hi Santosh, sorry for the late reply. Maybe there is some change in Apple Push Notification Services.
The code for sending push notification is the same. It should work regardless of Android or iOS.
I’m getting this exception
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.ssl.Alerts.getSSLException(Alerts.java:198)
at java.base/sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1974)
at java.base/sun.security.ssl.Handshaker.fatalSE(Handshaker.java:345)
at java.base/sun.security.ssl.Handshaker.fatalSE(Handshaker.java:339)
at java.base/sun.security.ssl.ClientHandshaker.checkServerCerts(ClientHandshaker.java:1968)
at java.base/sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1777)
at java.base/sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:264)
at java.base/sun.security.ssl.Handshaker.processLoop(Handshaker.java:1098)
at java.base/sun.security.ssl.Handshaker.processRecord(Handshaker.java:1026)
at java.base/sun.security.ssl.SSLSocketImpl.processInputRecord(SSLSocketImpl.java:1137)
at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1074)
at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
at java.base/sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1402)
at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1429)
at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
at java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:567)
at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1356)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1331)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:241)
at com.mindweaver.service.AndroidPushNotificationsService.sendPushNotification(AndroidPushNotificationsService.java:50)
at com.mindweaver.controller.NotificationController.send(NotificationController.java:49)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:290)
at java.base/sun.security.validator.Validator.validate(Validator.java:264)
at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:343)
at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:226)
at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:133)
at java.base/sun.security.ssl.ClientHandshaker.checkServerCerts(ClientHandshaker.java:1947)
… 67 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)