如何在使用服务帐户时刷新Google API令牌

时间:2016-12-15 13:15:42

标签: android google-api google-api-java-client service-accounts

我迷失在谷歌API Auth类型的迷宫中,令牌,程序,教程以及其他5个教程,样本,控制台的链接......

我正在使用服务帐户进行授权。但它在1小时后停止工作,我得到了:

com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
    at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
    at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
    at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
    at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
    at com.azimo.tool.androidPublisherService.AndroidPublisherAuth.init(AndroidPublisherAuth.java:36)
    at com.azimo.tool.androidPublisherService.AndroidPublisherService.<init>(AndroidPublisherService.java:24)

这就是我使用Google Api设置连接/授权的方式。就像我说它工作1小时:

public class AndroidPublisherAuth {

    private static final String CREDENTIAL_FILE_DIR = "credentials.p12";

    private static JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static HttpTransport HTTP_TRANSPORT;

    public static AndroidPublisher init(String applicationName,
                                    @Nullable String serviceAccountEmail) throws Exception {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(applicationName),
            "applicationName cannot be null or empty!");

        newTrustedTransport();
        Credential credential = authorizeWithServiceAccount(serviceAccountEmail);

        return new AndroidPublisher.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(applicationName)
            .build();
    }

    private static void newTrustedTransport() throws Exception {
        if (null == HTTP_TRANSPORT) {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        }
    }

    private static Credential authorizeWithServiceAccount(String serviceAccountEmail) throws Exception {
        return new GoogleCredential.Builder()
                .setTransport(HTTP_TRANSPORT)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(serviceAccountEmail)
                .setServiceAccountScopes(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER))
                .setServiceAccountPrivateKeyFromP12File(new File(CREDENTIAL_FILE_DIR))
                .build();
    }
}

如何刷新此连接? (我应该使用什么样的对象,我应该在项目中添加什么库,任何提示都没问题)

我有简单的Java项目而不是Android项目。

0 个答案:

没有答案