FireBase 發(fā)送消息推送

測試Google FireBase推送消息發(fā)送

public class FcmNotification {

    // This is the server-side app where you can access the Firebase Messaging service.
    // TODO: Replace with your own server key (can be found in the Firebase console under Project Settings > Cloud Messaging)
    private static final String SERVER_KEY = "your_server_key";

    // Sends a notification message to a specific device.
    public static void sendNotificationToUser(String token, String title, String body) {
        String message = "{\"to\":\"" + token + "\",\"notification\":{\"title\":\"" + title + "\",\"body\":\"" + body + "\"}}";
        sendMessage(message);
    }

    // Sends a notification message to a topic.
    public static void sendNotificationToTopic(String topic, String title, String body) {
        String message = "{\"to\":\"/topics/" + topic + "\",\"notification\":{\"title\":\"" + title + "\",\"body\":\"" + body + "\"}}";
        sendMessage(message);
    }

    // Sends a message using the FCM server protocol.
    private static void sendMessage(String message) {
        try {
            URL url = new URL("https://fcm.googleapis.com/fcm/send");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "key=" + SERVER_KEY);
            connection.setRequestProperty("Content-Type", "application/json");

            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(message.getBytes());
            }

            int responseCode = connection.getResponseCode();
            System.out.println("Response Code : " + responseCode);

            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }

                // Print result
                System.out.println(response.toString());
            }
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

your_server_key的位置

server_key
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容