Saturday, 17 September 2016

How to send Firebase Push Notification from HTTP server using java

Firebase HTTP server side code using java 


hello all

Before going to code , go through this link which will give you the format of the message as json that we are going to send as firebase push notification.

I am going to send below format json as push notification
 
 {
    "to" : "token which is received in android or ios app",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    },
    "data" : {
      "Nick" : "Mario",
      "Room" : "PortugalVSDenmark"
    }
  }

************************************************************

Now lets start coding :)

//import necessary packages  
import java.io.DataOutputStream;
import java.net.URL;
import java.util.HashMap;
import javax.net.ssl.HttpsURLConnection;
import org.json.simple.JSONObject;

public class Fcmtest {
/**
* @param args
*/
public static void main(String[] args) {
HttpsURLConnection con = null;
//FIREBASE_SERVER_KEY is nothing but server key that you got while creating firebase project in fcm
String FIREBASE_SERVER_KEY ="xxxxxxxxxxxxxxxx";
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("Nick", "Mario!");
data.put("Room", "PortugalVSDenmark");
JSONObject dataJsonObject = new JSONObject();
dataJsonObject.put("hello", "world");
dataJsonObject.put("marco", "polo");
JSONObject titleInfo = new JSONObject();
titleInfo.put("body","great match!");
titleInfo.put("icon","myicon");
titleInfo.put("title", "Portugal vs. Denmark");
JSONObject finalJsonMessage= new JSONObject();
finalJsonMessage.put("notification", titleInfo);
finalJsonMessage.put("data", dataJsonObject);
//replace xxxxxxxx with token that you got when your app run first time means when your device registered to receive fcm from firebase
finalJsonMessage.put("to", "xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
try{
String url = "https://fcm.googleapis.com/fcm/send";
URL obj = new URL(url);
con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
// Set POST headers
con.setRequestProperty("Authorization", "key="+FIREBASE_SERVER_KEY);
con.setRequestProperty("Content-Type", "application/json");
// Send POST body
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(finalJsonMessage.toJSONString());
wr.flush();
wr.close();
con.getResponseCode();
}
catch(Exception e){
e.printStackTrace();
}
}
}

Thank you
mithun

No comments:

Post a Comment