Home » Android » android – Complete FCM Java/Spring integration based on topic/token and groups of token-Exceptionshub

android – Complete FCM Java/Spring integration based on topic/token and groups of token-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I want to configure complete java program for pushing of FCM messages to the different mobiles based on topic and token. I have tried so many ways but its not working as expected. Anybody can help me to do this in an easier way?

Below method I created for doing post. But need more clarity.

private String sendNotification()  throws Exception {
        URL url = new URL(FCM_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");

        try {
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(root.toString());
            wr.flush();

            BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream())));

            String output;
            StringBuilder builder = new StringBuilder();
            while ((output = br.readLine()) != null) {
                builder.append(output);
            }
            System.out.println(builder);
            String result = builder.toString();

        }

            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
           return e.getMessage();
        }

    }
How to&Answers:

Authorization is missing in it.

conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);

You can refer the below answer. It contains complete solution for it.
https://stackoverflow.com/a/49206352/3405508