Ho già provato il seguente comando in Curl per inviare una notifica utilizzando l'API REST di Firebase e funziona:Qual è l'equivalente Java da utilizzare https://fcm.googleapis.com/fcm/send REST Api
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\"}"
Ora che sto cercando di fare lo stesso in Java, non ho trovato un modo semplice per fare lo stesso e niente di ciò che ho provato attiva la notifica nel mio endpoint mobile.
Questo è il mio approccio più vicino:
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();
}
Ma poi ottengo:
java.io.IOException: Server returned HTTP response code: 401 for URL: https://fcm.googleapis.com/fcm/send
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1625)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at httpclient.test.MyHttpClientPost.sendNotification(MyHttpClientPost.java:131)
at httpclient.test.MyHttpClientPost.main(MyHttpClientPost.java:26)
Grazie per una domanda ben scritta. Un semplice problema, ma hai fornito tutti i dettagli necessari a qualcuno per individuare il tuo problema e in realtà aiutare. Ancora più importante, questa domanda potrebbe aiutare qualcun altro in futuro, che è il "tutto punto" di StackOverflow, e tu hai contribuito molto bene a questo. [Perché sono così effusivo? Le domande ben scritte su SO sono una rarità, come sicuramente imparerai presto] –