FireBase 发送消息推送

测试Google FireBase推送消息发送

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容