【问题标题】:Download files from Google Storage using Java使用 Java 从 Google Storage 下载文件
【发布时间】:2016-01-15 12:46:12
【问题描述】:

我已成功地将数据从 Google Big Query 移动到 Google Storage 的过程自动化。现在我还需要以自动方式将数据从 Google Storage 下载到我的环境中。

我正在尝试执行正常的 HTTP 请求,但之前已授权。所以我的 HTTP 请求是

    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(authorize());
    GenericUrl url = new GenericUrl(uri);
    HttpRequest request = requestFactory.buildGetRequest(url);
    HttpResponse response = request.execute();
    String content = response.parseAsString();

我的授权码是

/** Authorizes the installed application to access user's protected data. */
    private static Credential authorize() throws Exception
    {
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        // load client secrets
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                new InputStreamReader(BigQueryConsumer.class.getResourceAsStream("/secret.json")));

        // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));

        // set up authorization code flow
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, JSON_FACTORY, clientSecrets,
                SCOPES).setDataStoreFactory(fileDataStoreFactory)
                .build();
        // authorize
        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }

以下常量在哪里

  1. CREDENTIALS_DIRECTORY : ".oauth-credentials"
  2. JSON_FACTORY : JacksonFactory.getDefaultInstance()
  3. SCOPES:只有“https://www.googleapis.com/auth/devstorage.full_control”的字符串列表
  4. HTTP_TRANSPORT:新的 NetHttpTransport()

在身份验证/授权过程中我遗漏了什么?我得到了

    Exception in thread "main" com.google.api.client.http.HttpResponseException: 401 Unauthorized
<HTML>
<HEAD>
<TITLE>Unauthorized</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Unauthorized</H1>
<H2>Error 401</H2>
</BODY>
</HTML>

【问题讨论】:

标签: java google-api google-cloud-storage google-api-java-client google-authentication


【解决方案1】:

对于寻找答案的其他人。要使用应用程序默认凭据,您需要执行几个步骤...您可以按照以下步骤操作,或查看此link

  1. 第一件事:安装谷歌云存储SDK
  2. 确保您可以从 SDK 运行命令。如果你没有安装python,你需要安装python 2.7或更高版本,还有pyopenssl...
  3. 您需要在 SDK 中通过运行 gcloud auth activate-service-account [服务帐户电子邮件] --key-fil e [.p12 文件](编辑方括号中的值)。当你运行它时,你应该会收到一条消息,告诉你你已经激活了你的服务帐户
  4. 您需要通过设置从 SDK 设置环境变量 GOOGLE_APPLICATION_CREDENTIALS 到密钥的 JSON 路径(从开发者控制台创建的服务帐户下载的路径) CLOUDSDK_PYTHON_SITEPACKAGES 为 1,同时设置项目

配置系统变量的命令...

设置 GOOGLE_APPLICATION_CREDENTIALS “secret.json 路径” 设置 CLOUDSDK_PYTHON_SITEPACKAGES 1 gcloud 配置设置项目“你的项目名称”

在您进行身份验证和授权后,您可以开始使用应用程序的默认凭据,前提是您已正确设置环境。

当您成功设置环境后,您就可以通过身份验证并获取默认凭据

GoogleCredential 凭证 = GoogleCredential.getApplicationDefault(); if (credential.createScopedRequired()) { credential = credential.createScoped(StorageScopes.all()); } HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); storageService = new Storage.Builder(httpTransport, jsonFactory, credential) .setApplicationName(applicationName).build();

并使用 HTTP GET 从您的谷歌存储桶中获取对象,即类似于以下内容

// 设置并执行 Google Cloud Storage 请求。 String uri = "https://storage.googleapis.com/" + URLEncoder.encode("[你的存储桶名称]", "UTF-8") + "/" + googleStorageFileName + "/" + fileName; httpTransport = GoogleNetHttpTransport.newTrustedTransport(); HttpRequestFactory requestFactory = httpTransport.createRequestFactory( 凭据); GenericUrl 网址 = 新的 GenericUrl(uri); HttpRequest 请求 = requestFactory.buildGetRequest(url); HttpResponse 响应 = request.execute(); 字符串内容 = response.parseAsString(); BufferedWriter writer = new BufferedWriter(new FileWriter(pathToSave + googleStorageFileName)); writer.write(内容);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-19
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    相关资源
    最近更新 更多