FCM 在一段时间后抛出 401 以进行数据消息通知



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

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);

此代码段用于获取 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();
}

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

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

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

最新更新