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