为生产Android应用获取Google Speech API访问令牌

时间:2017-03-30 10:09:04

标签: android google-speech-api google-cloud-speech

我在Android应用中使用Google Speech API。 README说明:      In this sample, we load the credential from a JSON file stored in a raw resource folder of this client app. You should never do this in your app. Instead, store the file in your server and obtain an access token from there.

是否有关于如何正确获取生产应用程序的访问令牌的示例?

从我收集到的内容来看,似乎我可以使用通过计算引擎或GAE提供的Application Default Credentials,但我不知道如何使用访问令牌实际响应我的应用。

2 个答案:

答案 0 :(得分:4)

我是样本的作者。

这是应该在服务器端的部分。基本上,您必须在服务器端安全地存储JSON文件,并在从移动应用程序收到请求时获取新的访问令牌。移动应用应始终与您的服务器通信以获取访问令牌。这样,您就不需要将服务帐户密钥放在APK中。

        // In response to a request from a mobile client

        // Open the JSON file stored on the server side.
        final InputStream stream = ...;
        try {
            // Initialize the credentials
            final GoogleCredentials credentials =
                GoogleCredentials.fromStream(stream)
                    .createScoped(SCOPE);
            // Fetch a new access token.
            final AccessToken token = credentials.refreshAccessToken();

            // Return the token to the mobile app.

        } catch (IOException e) {

            // Maybe report this as an HTTP error.

        }

如果您不在服务器端使用Java,则可以找到您在Google Cloud Client Libraries使用的语言的客户端库。

有关如何将请求从后端发送到API的基础知识,请参阅Google Cloud Platform Auth Guide

答案 1 :(得分:1)

对于Android,您可能希望使用Android sample for Google Cloud Speech,因为云客户端库目前不关注Android支持。