测试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的位置