java 如何获取Android上Firebase Cloud Messaging API(V1)的访问令牌?

ahy6op9u  于 7个月前  发布在  Java
关注(0)|答案(2)|浏览(95)

如何获取Firebase Cloud Messaging API(V1)的访问令牌。虽然我已经完成了所有必要的步骤,但我无法获取访问令牌。
我正在使用以下代码结构,但我得到以下错误:
java.lang.NullPointerException:尝试对空对象引用调用虚拟方法“java.lang.String com.google.auth.oauth2.getTokenValue()”
service_account文件位置:app\src\main\assets

private String getAccessToken() throws IOException {
        String MESSAGING_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
        String[] SCOPES = { MESSAGING_SCOPE };
        InputStream serviceAccountStream = getAssets().open("service_account.json");
        GoogleCredentials googleCredentials = GoogleCredentials
                .fromStream(serviceAccountStream)
                .createScoped(Arrays.asList(SCOPES));
        googleCredentials.refreshAccessToken();
        return googleCredentials.getAccessToken().getTokenValue();
    }

    private void sendFCMNotificationToPostOwner(String user_is_pro, String user_fcm_token, String notificationTitle, String notificationBody) {
        ExecutorService executor = Executors.newFixedThreadPool(1);
        Future<String> futureToken = executor.submit(() -> {
            try {
                return getAccessToken();
            } catch (IOException e) {
                Log.d("TAGFCM", "eun_exdsds: " + e.getMessage());
                e.printStackTrace();
                return "null";
            }
        });

        try {
            Log.d("TAGFCM", "eun_exdsds: " + futureToken.get());
            String bearerToken = futureToken.get();
            final String FCM_API = "https://fcm.googleapis.com/v1/projects/project-pro/messages:send";
            AsyncTask.execute(() -> {
                try {
                    OkHttpClient client = new OkHttpClient();
                    String jsonBody = "{\"message\":{\"token\":\"" + user_fcm_token + "\", \"notification\":{\"title\":\"" + notificationTitle + "\", \"body\":\"" + notificationBody + "\"}}}";
                    RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);
                    okhttp3.Request request = new okhttp3.Request.Builder()
                            .url(FCM_API)
                            .post(body)
                            .addHeader("Authorization", "Bearer " + bearerToken)
                            .addHeader("Content-Type", "application/json")
                            .build();

                    okhttp3.Response response = client.newCall(request).execute();
                    Log.d("TAGFCM", "response: " + response.message());
                } catch (IOException e) {
                    Log.d("TAGFCM", "exception" +e.getMessage());
                    e.printStackTrace();
                }
            });

        } catch (InterruptedException | ExecutionException e) {
            Log.d("TAGFCM", "" + e.getMessage()+" ");
            e.printStackTrace();
        }

        executor.shutdown();
    }

字符串

raogr8fs

raogr8fs1#

private static final String MESSAGING_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
private static final String[] SCOPES = {MESSAGING_SCOPE};

private void copyToFileDir() {
    try {
        File file = new File(getFilesDir(), "service-account.json");
        if (!file.exists()) {
            String readFile = readFromAssets("service-account.json");
            OutputStream out = new FileOutputStream(file);
            assert readFile != null;
            out.write(readFile.getBytes());
            out.flush();
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private String getAccessToken() {
    try {
        File file = new File(getFilesDir(), "service-account.json");
        FileInputStream stream = new FileInputStream(file);
        GoogleCredentials googleCredentials = GoogleCredentials.fromStream(stream)
                .createScoped(Arrays.asList(SCOPES));
        googleCredentials.refresh();
        return googleCredentials.getAccessToken().getTokenValue();
    } catch (Exception e) {
        return e.getMessage();
    }
}

@Nullable
private String readFromAssets(String filename) {
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open(filename)));
        StringBuilder sb = new StringBuilder();
        String mLine = reader.readLine();
        while (mLine != null) {
            sb.append(mLine).append('\n'); // process line
            mLine = reader.readLine();
        }
        reader.close();
        return sb.toString();
    } catch (IOException e) {
        return e.getMessage();
    }
}

字符串

ygya80vv

ygya80vv2#

private String getAccessToken() {
    try {
        File file = new File(getFilesDir(), "service-account.json");
        FileInputStream stream = new FileInputStream(file);
        GoogleCredentials googleCredentials = GoogleCredentials.fromStream(stream)
            .createScoped(Arrays.asList(SCOPES));
        //googleCredentials.refresh();
        return googleCredentials.refreshAccessToken().getTokenValue();
    } catch (Exception e) {
        return e.getMessage();
    }
}

字符串
请在刷新getTokenValue时立即执行此操作。

相关问题