What is the Java equivalent for using https://fcm.googleapis.com/fcm/send REST Api

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://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) 
+5
source share
1 answer

401 means unauthorized access, so no valid Authorization header was sent.

And this line:

 httpcon.setRequestProperty("Authorization: key", "AIza...iD9wk"); 

Not equivalent to -H "Authorization: key=AIza...iD9wk" . The first argument should be the name of the header, which is Authorization :

 httpcon.setRequestProperty("Authorization", "key=AIza...iD9wk"); 

In conclusion, you misunderstood how the HTTP header is formatted. Basically, the name and value of the header are separated : not = .

+5
source

All Articles