I already tried the following command in Curl to send a notification using Firebase REST Api, and it works:
curl -X POST --header "Authorization: key=AIza...iD9wk" --Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d "{\"notification\":{\"title\": \"My title\", \"text\": \"My text\", \"sound\": \"default\"}, \"to\": \"cAhmJfN...bNau9z\"}"
Now, when I try to do the same in Java, I could not find an easy way to do the same, and none of what I tried triggers a notification in my mobile endpoint.
This is my closest approach:
try { HttpURLConnection httpcon = (HttpURLConnection) ((new URL("https://fcm.googleapis.com/fcm/send").openConnection())); httpcon.setDoOutput(true); httpcon.setRequestProperty("Content-Type", "application/json"); httpcon.setRequestProperty("Authorization: key", "AIza...iD9wk"); httpcon.setRequestMethod("POST"); httpcon.connect(); System.out.println("Connected!"); byte[] outputBytes = "{\"notification\":{\"title\": \"My title\", \"text\": \"My text\", \"sound\": \"default\"}, \"to\": \"cAhmJfN...bNau9z\"}".getBytes("UTF-8"); OutputStream os = httpcon.getOutputStream(); os.write(outputBytes); os.close(); // Reading response InputStream input = httpcon.getInputStream(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) { for (String line; (line = reader.readLine()) != null;) { System.out.println(line); } } System.out.println("Http POST request sent!"); } catch (IOException e) { e.printStackTrace(); }
But then I get:
java.io.IOException: Server returned HTTP response code: 401 for URL: https:
source share