【问题标题】:FCM throws 401 after some time for data message notificationFCM 在数据消息通知一段时间后抛出 401
【发布时间】:2020-06-07 12:40:58
【问题描述】:

我正在从 Java 应用服务器向 FCM 休息端点发送数据消息通知。一切正常,应用程序接收到数据消息没有任何问题,但是一段时间后(没有任何明显的趋势),FCM 星返回 401。我正在使用 Apache common 的 HTTPClient 库进行 http 调用。这是相关代码sn -p

final HttpPost httpPost = new HttpPost("https://fcm.googleapis.com/v1/projects/proj1/messages:send");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer "+ accessToken);
responseBody = httpclient.execute(httpPost, responseHandler);

这个sn-p是用来获取API授权的访问令牌

 static{
             FileInputStream refreshToken = null;
             refreshToken = new FileInputStream("C:/prj/proserviceaccoutkey.json");
             googleCredentials=GoogleCredentials.fromStream(refreshToken).createScoped("https://www.googleapis.com/auth/firebase.messaging");
             options = new FirebaseOptions.Builder() .setCredentials(googleCredentials).build();
    }

// Gets called each time a data message needs to be sent
  public static synchronized String getAccessToken()
    {
        if(googleCredentials.getAccessToken()==null)
            try {
                googleCredentials.refresh();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return googleCredentials.getAccessToken().getTokenValue();
    }

【问题讨论】:

    标签: firebase firebase-cloud-messaging


    【解决方案1】:

    看起来 googleCredentials.getAccessToken() 将始终返回非空值,即使 cahce 令牌不再有效,这就是为什么令牌没有在代码中刷新。应用了以下修复程序,它现在正在工作。

    public static synchronized String getAccessToken()
        {
            if(googleCredentials!=null)
                try {
                    googleCredentials.refresh();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return googleCredentials.getAccessToken().getTokenValue();
        }
    

    虽然,它并没有真正使用缓存的令牌,因为每次它都会刷新令牌,但我的问题现在已经解决了。

    【讨论】:

      猜你喜欢
      • 2017-02-23
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多