0

I know the risk of doing this.

But right now I only want to send message from one device to another device without any server.

Here is what I'm try.

        JSONObject root = new JSONObject();
        JSONObject notification = new JSONObject();
        notification.put("body", messageText);
        notification.put("title", username);

        JSONObject data = new JSONObject();
        data.put("senderToken", senderToken);
        data.put("messageId", messageId);

        root.put("notification", notification);
        root.put("data", data);
        root.put("to", receiverToken);

        String postData = URLEncoder.encode(root.toString(),"UTF-8");
        return openServerConnection(postData);

private String openServerConnection(String postData){

    try {
        URL url = new URL("https://fcm.googleapis.com/fcm/send");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestProperty("Content-Type","application/json");
        httpURLConnection.setRequestProperty("Authorization", "key=AAAAPQ4yGQM:APA9....1cW");
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        OutputStream outputStream = httpURLConnection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(outputStream, "UTF-8") );
        bufferedWriter.write(postData);
        bufferedWriter.flush();
        bufferedWriter.close();
        outputStream.close();
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream, "iso-8859-1") );
        StringBuilder result = new StringBuilder();
        String line = "";
        while( (line = bufferedReader.readLine()) != null ){
            result.append(line);
        }
        bufferedReader.close();
        inputStream.close();
        httpURLConnection.disconnect();
        return result.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

But I'm seeing an error.

W/System.err: java.io.FileNotFoundException: https://fcm.googleapis.com/fcm/send at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:250) W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210) at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java) at org.octabyte.zeem.InstantChat.SendMessage.openServerConnection(SendMessage.java:124) W/System.err: at org.octabyte.zeem.InstantChat.SendMessage.doInBackground(SendMessage.java:74) at org.octabyte.zeem.InstantChat.SendMessage.doInBackground(SendMessage.java:21) at android.os.AsyncTask$2.call(AsyncTask.java:304) at java.util.concurrent.FutureTask.run(FutureTask.java:237) W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) W/System.err: at java.lang.Thread.run(Thread.java:761)

I'm not able to send any message, I checked my firebase token all are correct and server key also then what is the problem. Can you please let me know about this what I'm missing.

And second thing is I see the build in method already there for sending some kind of messages. But it's not working. What is the purpose of this method can you please let me know about this

Here is the code of this method. Can you please explain it.

RemoteMessage message = new RemoteMessage.Builder(getRegistrationToken())
                .setMessageId(incrementIdAndGet())
                .addData("message", "Hello")
                .build();

FirebaseMessaging.getInstance().send(message);

What is this ????

Update

in documentation there described how you can send firebase messages using http request. right here Build App Server Send Requests can I use this method to send request from android device. Because in this method server key is not required. Can some body let me know about this is it possible or not ?

  • 1
    the best way to use fcm server,node js, handles everything, you don't need to configure.Just copy paste the commands. – hemen Aug 27 '18 at 11:47
  • I think you are using wrong URL. Documentation is using another url: https://firebase.google.com/docs/cloud-messaging/send-message – Vladyslav Matviienko Aug 27 '18 at 12:16
  • 1
    You should not follow this approach as it will expose your server key in apk. Even if you want to do so this might help you https://stackoverflow.com/questions/37990140/how-to-send-one-to-one-message-using-firebase-messaging – rmdroid Aug 27 '18 at 12:16
  • @rmdroid Yes, I'm already following this answer. But I'm getting error as I described in my question – World Programing Aug 27 '18 at 12:36
  • "Because in this method server key is not required. Can some body let me know about this is it possible or not ?" There is no way to send messages **to** devices without knowing the FCM server key. The page you linked has that key in `Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA`. – Frank van Puffelen Aug 27 '18 at 14:11
  • @FrankvanPuffelen It is **Oauth 2.0 token for the service account** not the **server key** Isn't it a safe way ? As I understand in this way you don't need server key – World Programing Aug 27 '18 at 17:07
  • Getting that OAuth token is based on a service account: https://firebase.google.com/docs/cloud-messaging/auth-server. – Frank van Puffelen Aug 27 '18 at 19:28
  • @FrankvanPuffelen Yes, I did the same thing and place `service_account.json` in `assets` directory. Everything is working But I want to know is it a safe way ? – World Programing Aug 28 '18 at 01:13
  • Putting the service_account.json in an app that you share with your users is **incredibly insecure**. Any malicious can get that JSON out of the APK and will then have full access to your entire Firebase project. As you've seen before: there is no secure way to send device to device messages with (just) Firebase Cloud Messaging. – Frank van Puffelen Aug 28 '18 at 03:06
  • @FrankvanPuffelen is there no way to **encrypt** file and **decrypt** on runtime. Id someone get the file from APK. He is not able to get information from encrypted file. Isn't it possible ? – World Programing Aug 28 '18 at 06:26
  • If your code can decrypt the file, so can a malicious user. – Frank van Puffelen Aug 28 '18 at 12:57

1 Answers1

1

I test it and run your code. the problem is in postData You are encoding json data which case the problem. Just replace this line

      String postData = URLEncoder.encode(root.toString(),"UTF-8");
      // replace with
      String postData = root.toString();
Azeem Haider
  • 1,443
  • 4
  • 23
  • 41