Ali Bdeir
Ali Bdeir

Reputation: 4375

Sending FCM message from client not working

Note: I am well aware of the dangers of exposing my API Key. This is a personal app.


I'm using this:

String urlString = "https://fcm.googleapis.com/fcm/send";
        JSONObject jsonObjects = new JSONObject();
        try {
            jsonObjects.put("title", titleET.getText().toString());
            jsonObjects.put("body", textET.getText().toString());
            jsonObjects.put("to","/topics/subscribed");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(JSON, jsonObjects.toString());
        Request req = new Request.Builder()
                .url(urlString)
                .post(body)
                .addHeader("Authorization","key=AAAA0lrtzQs:APA91bHiergBa6_A5KEVlV00LiovITBwnkZfgoGEUx-Ofg4hnk48A_nEyTwwpyriOOHHM96ZkDiUeUgpPOApSS4zaivtRKxP4dQjdwH7CFROR5l51ZA85jaFgMa5VmSsu8_yqUb4kc1U")
                .build();
        try {
            Response res = client.newCall(req).execute();
            if (!res.isSuccessful()) {
                throw new UnknownError("Error: " + res.code() + " " + res.body().string());
            }
            Log.d("MainActivity", res.body().toString());
        } catch (IOException e) {
            send();
        }

And nothing is being sent.

If I use the Firebase Console everything is working fine. When I do this request nothing even shows up in the console. What am I missing?

Upvotes: 0

Views: 2661

Answers (1)

Bob Snyder
Bob Snyder

Reputation: 38319

One problem is that you are not building the JSON for a notification correctly. It should be:

    JSONObject notif = new JSONObject();
    JSONObject jsonObjects = new JSONObject();
    try {
        notif.put("title", titleET.getText().toString());
        notif.put("body", textET.getText().toString());
        jsonObjects.put("notification", notif);
        jsonObjects.put("to","/topics/subscribed");
    } catch (JSONException e) {
        e.printStackTrace();
    }

That won't cause the message to not be sent, but may muddle your expected results.

I was able to copy your code, fill in the missing pieces, and successfully send and receive a message to a topic.

The "missing pieces" I added:

    final OkHttpClient client = new OkHttpClient();
    final MediaType JSON = MediaType.parse("application/json");

For authorization key, I used the "Server key" shown in the Cloud Messaging tab of the Firebase console settings for my project.

Upvotes: 3

Related Questions