Java Server — send Push with POST to google Firebase Cloud

梦想的初衷 提交于 2019-12-20 07:14:39

问题


After I tested the push notifications are working with Postman I'd like to send a push request to FCM when I am sending a message in my app. The function called is going to my Java server and call a function like :

@POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response sendMsg(Message m) throws ExceptionFacade {
...
}

So each time I call this function I'd like to send a POST request to https://fcm.googleapis.com/fcm/send with a json.

I want to know if there is already a code ready for a java server ? and also some help how to implement it.

Also I don't understand if I can use a php file to do it (I find things like this https://github.com/Paragraph1/php-fcm ). I am using angularjs.

Thank you guys !


回答1:


Here is the final code working well ! It is sending a json like this :

{
 "to" : "...",
 "priority" : "high",
 "notification" : {
                   "title" : "hello",
                   "body" : "me"
  }
}

//Don't forget to add common-codec and common-login jar for build success.

public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws JSONException, IOException {

                HttpClient client = HttpClientBuilder.create().build();
                HttpPost post = new HttpPost("https://fcm.googleapis.com/fcm/send");
                post.setHeader("Content-type", "application/json");
                post.setHeader("Authorization", "key=FCM-API-KEY");
                JSONObject message = new JSONObject();
                message.put("to", "TOKEN-FCM-OF-THE-DEVICE");
                message.put("priority", "high");
                JSONObject notification = new JSONObject();
                notification.put("title", "Me");
                notification.put("body", "New message");
                message.put("notification", notification);
                post.setEntity(new StringEntity(message.toString(), "UTF-8"));
                HttpResponse response = client.execute(post);

                System.out.println(response);
                System.out.println(message);
    }


来源:https://stackoverflow.com/questions/39159704/java-server-send-push-with-post-to-google-firebase-cloud

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!