从GoogleCredential获取访问令牌时出错

问题描述

我正在尝试获取访问令牌,以使用Cloud SQL Admin API将表格以CSV格式导出到Google云存储。我不断收到此错误:每次在下面的代码中调用Scopes not configured for service account. Scoped should be specified by calling createScoped or passing scopes to constructor.时,都会 credentials.refreshAccessToken();。 有人可以指导我关于我在这里做错了什么


       Set<String> oAuthScopes = new HashSet<String>();
       oAuthScopes.add(SQLAdminScopes.CLOUD_PLATFORM);
       oAuthScopes.add(SQLAdminScopes.SQLSERVICE_ADMIN);

       GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
       credentials.createScoped(oAuthScopes);
       AccessToken access_token = credentials.refreshAccessToken();

        try {

            httppost.addRequestHeader("Content-Type","application/json");
            httppost.addRequestHeader("Authorization","Bearer " + access_token.getTokenValue());

            httppost.setRequestEntity(
                    new StringRequestEntity(
                            "{\"exportContext\":" +
                                    "\"fileType\": \"CSV\"," +
                                    "\"uri\":" + EXPORT_BUCKET +
                                    "\"databases\": [\"" + DATABASE_NAME + "\"]," +
                                    "\"csvExportOptions\": " +
                                    "{" +
                                    "\"selectQuery\":\"" + SQL_QUERY + "\" " +
                                    "} " +
                                    "} " +
                                    "}","application/json","UTF-8"));

            httpclient.executeMethod(httppost);
            String response = new String(httppost.getResponseBody());
            httppost.releaseConnection();
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
            unsupportedEncodingException.printStackTrace();
        }

解决方法

此异常似乎来自以下事实:一旦您设置了“ GOOGLE_APPLICATION_CREDENTIALS”,客户端libraries的“应用程序默认凭据”授权策略便会生效。

此外,您可以创建如下范围的凭据:

GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...