How to send a push notification to an Android device using FCM using a java server?

I wrote this code to send a notification using fcm using the java server code. But it throws an exception Returning server-side HTTP response code: 500 for URL: https://fcm.googleapis.com/fcm/send

public static void pushFCMNotification(String userDeviceIdKey) throws Exception{ String authKey = AUTH_KEY_FCM; // You FCM AUTH key String FMCurl = API_URL_FCM; URL url = new URL(FMCurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization","key="+authKey); conn.setRequestProperty("Content-Type","application/json"); JSONObject json = new JSONObject(); json.put("to",userDeviceIdKey.trim()); JSONObject info = new JSONObject(); info.put("title", "Notificatoin Title"); // Notification title info.put("body", "Hello Test notification"); // Notification body json.put("notification", info); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(json.toString()); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + json); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); /*OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(json.toString()); wr.flush(); conn.getInputStream();*/ } 
0
source share
1 answer

According to official documentation:

Errors in the range 500-599 (for example, 500 or 503) indicate an internal error on the FCM connection server when trying to process the request or that the server is temporarily unavailable (for example, due to timeouts). The sender must try again later, observing the Retry-After header included in the response. Application servers must provide exponential shutdown.

source: https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream

However, make sure the JSON request is formatted correctly. Try updating your question using json.toString() and make sure your API key is still valid using the procedure described in: Verifying the server key is correct

+1
source

All Articles