微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从GoogleCredential获取访问令牌时出错

如何解决从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"));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。