gpt4 book ai didi

java - 来自 Java 而不是 Firebase 控制台的 Firebase 云消息传递通知

转载 作者:IT老高 更新时间:2023-10-28 21:16:00 32 4
gpt4 key购买 nike

我是 Firebase 的新手,当我的 Java 应用程序尝试使用客户端的 Firebase token 发送通知/消息时,我遇到了错误,例如发件人 ID 不匹配和 HTTP 状态为 401 的身份验证错误。请注意,使用 Firebase 控制台,我可以将消息发送到客户端。

对于客户端应用,我做了以下操作:

  1. 从这里克隆的 Firebase messaging 快速入门应用 -- https://github.com/firebase/quickstart-android/tree/master/messaging -- 已经设置了 Firebase 依赖项等。在 Android Studio 中加载克隆的应用程序。
  2. 使用 Firebase 控制台,创建了一个名为 My Notification Client 的新项目,并使用 com.google.firebase.quickstart.fcm 作为 Android 的包名添加了一个应用应用程序。
  3. 为添加到新创建项目的 Android 应用下载 google-services.json 文件,并将其复制到 messaging/app/ 文件夹并与 Grade 同步Android Studio 中的文件。
  4. 创建了一个模拟器并在 Android Studio 中运行该应用程序。当应用程序在模拟器中加载后,单击 Log Token 按钮以在 Android StudioAndroid Monitor 选项卡中捕获客户端的 Firebase token 。
  5. 使用 Firebase 控制台,选择新创建的项目 My Notification Client,点击左侧 Pane 中的 Notifications 链接,并通过粘贴 Firebase 向设备发送通知上一步中捕获的 token 。

效果很好!下一步是使用单独的简单 Java 应用程序(最终将成为通知服务器)将通知发送到客户端,而不是使用 Firebase 控制台。

为此,我按照此处列出的步骤进行操作——https://firebase.google.com/docs/server/setup#prerequisites .具体来说,这些是我执行的步骤:

  1. 在 Firebase 控制台中创建了一个名为 My Notification Server 的新项目。
  2. 在 Firebase 控制台中使用 Settings > Permissions,创建一个新的服务帐户并下载 serviceAccountCredentials.json 文件。
  3. 在Eclipse中新建一个maven项目,在pom.xml中添加如下依赖:
    <dependency>
<groupId>com.google.gcm</groupId>
<artifactId>gcm-server</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-server-sdk</artifactId>
<version>3.0.0</version>
</dependency>
  1. 然后,我扩展了 com.google.android.gcm.sender.Sender 以创建 FCMSender 并覆盖 protected 方法 getConnection(String url) 使用新的 FCM 端点,如下所示:

    class FCMSender extends Sender {

    public FCMSender(String key) {
    super(key);
    }

    @Override
    protected HttpURLConnection getConnection(String url) throws IOException {
    String fcmUrl = "https://fcm.googleapis.com/fcm/send";
    return (HttpURLConnection) new URL(fcmUrl).openConnection();
    }
    }
  2. 我的 Java 应用程序的 main() 方法如下所示:

    public static void main(String[] args) {
    // Obtain serverKey from Project Settings -> Cloud Messaging tab
    // for "My Notification Client" project in Firebase Console.
    String serverKey = <get_server_key_from_firebase_console>;
    Thread t = new Thread() {
    public void run(){
    try {
    Sender sender = new FCMSender(serverKey);
    Message message = new Message.Builder()
    .collapseKey("message")
    .timeToLive(3)
    .delayWhileIdle(true)
    .addData("message", "Notification from Java application");
    .build();

    // Use the same token(or registration id) that was earlier
    // used to send the message to the client directly from
    // Firebase Console's Notification tab.
    Result result = sender.send(message,
    "APA91bFfIFjSCcSiJ111rbmkpnMkZY-Ej4RCpdBZFZN_mYgfHwFlx-M1UXS5FqDBcN8x1efrS2md8L9K_E9N21qB-PIHUqQwmF4p7Y3U-86nCGH7KNkZNjjz_P_qjcTR0TOrwXMh33vp",
    1);
    System.out.println("Result: " + result.toString());
    } catch (Exception e) {
    e.printStackTrace();
    }
    };
    t.start;
    try {
    t.join();
    }
    catch (InterruptedException iex) {
    iex.printStackTrace();
    }
    }

当我运行 Java 应用程序时,我收到 MismatchSenderId 错误。我尝试使用 curl 进行故障排除,如下所示,但得到了相同的错误:

$ skey=<obtained_from_project_settings_cloud_messaging_tab_in_firebase_console>
$ curl -X POST --header "Authorization: key=$skey" \
--Header "Content-Type: application/json" \
https://fcm.googleapis.com/fcm/send \
-d "{\"to\":\"APA91bFfIFjSCcSiJ111rbmkpnMkZY-Ej4RCpdBZFZN_mYgfHwFlx-M1UXS5FqDBcN8x1efrS2md8L9K_E9N21qB-PIHUqQwmF4p7Y3U-86nCGH7KNkZNjjz_P_qjcTR0TOrwXMh33vp\",\"data\":{\"message\":\"Yellow\"}}"

{"multicast_id":7391851081942579857,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

我尝试使用 Firebase 控制台中 My Notification Server 项目的 Project Settings > Cloud Messaging 选项卡上列出的 Server Key Project Number 但导致 InvalidRequestException: HTTP Status Code: 401.

错误代码的 Firebase 文档说明了关于 MismatchSenderId:

Mismatched Sender 200 + error:MismatchSenderId
A registration token is tied to a certain group of senders. When a client app registers for FCM, it must specify which senders are allowed to send messages. You should use one of those sender IDs when sending messages to the client app. If you switch to a different sender, the existing registration tokens won't work.

我不知道在 Firebase 控制台中的何处/如何配置 Android 应用(已添加到 My Notification Client 项目)以能够接收消息。

对此的任何帮助,将不胜感激!

最佳答案

我最近也开始使用 Firebase,之前没有 Google Cloud Messaging 方面的经验。 AFAIK,目前没有用于 Firebase 云消息传递的服务器端 SDK。

要将通知/消息从您的应用服务器发送到您的移动客户端,您需要实现自己的 HTTP 和/或 XMPP 方法。见 https://firebase.google.com/docs/cloud-messaging/

我的测试代码,使用 HTTP:

public CompletableFuture<String> fcmTest1() {
// https://firebase.google.com/docs/cloud-messaging/http-server-ref
String host = "fcm.googleapis.com";
String requestURI = "/fcm/send";
String CLIENT_TOKEN = "ASK_YOUR_MOBILE_CLIENT_DEV"; // https://developers.google.com/instance-id/

CompletableFuture<String> fut = new CompletableFuture<>();
JsonObject body = new JsonObject();
// JsonArray registration_ids = new JsonArray();
// body.put("registration_ids", registration_ids);
body.put("to", CLIENT_TOKEN);
body.put("priority", "high");
// body.put("dry_run", true);

JsonObject notification = new JsonObject();
notification.put("body", "body string here");
notification.put("title", "title string here");
// notification.put("icon", "myicon");

JsonObject data = new JsonObject();
data.put("key1", "value1");
data.put("key2", "value2");

body.put("notification", notification);
body.put("data", data);

HttpClientRequest hcr = httpsClient.post(443, host, requestURI).handler(response -> {
response.bodyHandler(buffer -> {
logger.debug("FcmTest1 rcvd: {}, {}", response.statusCode(), buffer.toString());
if (response.statusCode() == 200) {
fut.complete(buffer.toString());
} else {
fut.completeExceptionally(new RuntimeException(buffer.toString()));
}
});
});
hcr.putHeader("Authorization", "key=" + Utils.FIREBASE_SERVER_KEY)
.putHeader("content-type", "application/json").end(body.encode());
return fut;
}

注意:http 客户端和 json 由 vertx ( http://vertx.io/ ) 提供,但希望代码能够清楚地显示正在发生的事情,以便您可以随意使用。

关于java - 来自 Java 而不是 Firebase 控制台的 Firebase 云消息传递通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37426542/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com