開始使用 Cloud Storage

Google 多媒體和Video 360 會自動儲存實體讀取檔案 Google Cloud Storage 中。這些檔案僅供以下使用者存取 獲得存取權的帳戶。

建立專案

建立專案並設定專案如下:

  1. 前往 Google API 控制台「已啟用的 API」頁面

    如果您尚未登入 Google,系統會提示您登入。

  2. 在專案下拉式選單中選取現有專案,或建立新專案。
    • 如有多個現有專案,請務必選取專案 選取要啟用 Google Cloud Storage 的叢集 按一下 [Continue] (繼續)
    • 如果您沒有專案,請選取「建立新專案」,輸入專案名稱,然後選取「建立」

      注意:請注意部分資源 ID (例如專案 ID) 可能會在專案生命週期結束後保留下來。 因此,請避免將機密資訊儲存在資源中 識別碼

  3. 在「已啟用的 API」清單中,確認 Google Cloud Storage 元件已列出。 如果未列出,請按一下「Google API」分頁標籤,搜尋並選取 Google Cloud Storage 元件,然後按一下「啟用 API」

    請注意,大多數專案已啟用 Google Cloud Storage 元件。如果您計劃 使用 JSON API 存取 Google Cloud Storage,然後 您也應該確認 Google Cloud Storage JSON API 已啟用。

  4. 啟用專案的計費功能。

    您必須先為 專案。啟用計費功能不一定 表示您須支付費用詳情請參閱「定價」。

    1. 接著在雲端儲存空間專案中按一下左上角的圖庫選單,然後選取「帳單」
    2. 如果您還沒有帳單帳戶,請按照操作說明 建立新的帳單帳戶
    3. 如果您已經有現有的帳單帳戶, 然後選取「設定帳戶」

在 Google API 控制台中,留在同一個專案內前往下一個部分。

設定 Cloud Storage 的存取權

  1. 還是在所需專案的 Google API 控制台中,按一下圖片庫選單裡的 選取左上角的 [API 和]憑證。每月中的特定幾天 「憑證」頁面,找出「服務帳戶金鑰」

    找出服務帳戶金鑰電子郵件地址:

    1. 選取「服務帳戶金鑰」區段右側的「管理服務帳戶」連結。
    2. 系統隨即會在產生的「權限」頁面中顯示電子郵件地址

    如果沒有服務帳戶金鑰,請建立新的服務帳戶:

    1. 選取「建立憑證」下拉式選單,然後選擇「服務帳戶金鑰」
    2. 在「服務帳戶」下拉式選單中,選擇「新增服務帳戶」
    3. 在「Name」(名稱) 中輸入服務帳戶的名稱。系統會自動儲存「服務帳戶 ID」 名稱和專案名稱所產生的費用
    4. 記下服務帳戶 ID gserviceaccount.com 的電子郵件地址。 選取「建立」後,「憑證」頁面就不會顯示這項資訊。
    5. 在「金鑰類型」區段中,選擇「JSON」
    6. 點選「建立」。含有帳戶公開/私密金鑰組的 JSON 檔案會儲存至 您的「下載」資料夾。這組金鑰用於驗證 API 應用程式 簽署所有傳送至 API 的要求將產生的 JSON 檔案儲存在安全的地方 讓應用程式能夠存取該功能
  2. 與螢幕聯絡,可要求啟用實體讀取檔案功能的 Video 360 支援團隊 和/或 Google Bid Manager API

    支援團隊確認存取權後,請建立專屬的 Google 群組 並更新「Display &Video」中的下列欄位Video 360 合作夥伴詳細資料 (請注意,只有使用者 擁有夥伴層級存取權即可進行下列更新:

    • 記錄讀取 Google 群組
      唯讀群組只具備讀取檔案和列出儲存空間值區內容的權限。
    • 記錄管理 Google 網路論壇
      管理群組具備唯讀群組的所有權限,但也能變更 值區中檔案的 ACL。請注意,即使是管理群組也沒有權限 變更值區 ACL,也沒有建立、修改或刪除檔案的權限。

    新增 Google 群組後,您可以視需要新增或移除 Google 群組中的使用者 而無須再使用 Display &Video 360Video 360 支援團隊僅限這些使用者 群組成員將可存取您的資料。

存取您的資料

使用 gsutil 存取資料

gsutil 工具是一款指令列應用程式,可讓您存取 Google Cloud Storage 資料,完全不需程式設計 無須專人管理舉例來說,您可以在指令碼或批次檔案中使用 gsutil,而不是 以及建立自訂應用程式

如要開始使用 gsutil,請參閱 gsutil 說明文件。 您仍然必須像之前一樣使用 OAuth 2 進行驗證,不過 gsutil 會提示您 憑證,然後儲存供日後使用。

透過程式存取資料

Google Cloud Storage 提供適用於多種程式設計語言的 API 以程式輔助的方式存取資料以下範例說明如何執行 下載其中一個實體讀取檔案Google Cloud Storage 載入物件。別忘了,只有公開 實體讀取檔案會儲存在 gdbm-public 個值區;您的私人 實體讀取檔案會儲存在合作夥伴和廣告主的值區中。

Java

以下範例使用 API 專用 API 用戶端程式庫,可讓您存取 Google 簡單易用的 Cloud Storage除了主要的一般 Google API 用戶端程式庫 您也需要下載 程式庫 Cloud Storage API 專用指南

您必須先設定憑證,在與 API 通訊時 取得資料存取權限方法是建立 Credential 這個物件會使用服務帳戶的 developer.gserviceaccount.com 電子郵件地址 做為 ServiceAccountId,並載入已下載的私密金鑰檔案 透過 Google API 控制台建立服務帳戶這能確保 日後向 API 發出的要求都會以服務帳戶私密金鑰簽署:

NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JacksonFactory JSON_FACTORY = new JacksonFactory();

...

Credential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
   .setJsonFactory(JSON_FACTORY)
   .setServiceAccountId("...@developer.gserviceaccount.com")
   .setServiceAccountScopes(StorageScopes.DEVSTORAGE_READ_ONLY)
   .setServiceAccountPrivateKeyFromP12File(new File("...-privatekey.p12"))
   .build();

建立 Credential 物件後,即可使用該物件將 新的 Storage 物件,可以用於日後所有對 Google Cloud Storage API:

Storage storage = new Storage(HTTP_TRANSPORT, JSON_FACTORY, credential);

現在您已建立新的 Storage 物件,可以開始向 並嚴謹測試及提升 API 的公平性後 我們才能放心地推出 API你提出了擷取特定項目 bucketObjectName 的要求 值區 bucket程式庫會處理從 Google Cloud Storage,只要將內容輸出到 主控台:

Get bucketObject = storage.objects().get(bucketName, bucketObjectName);

ByteArrayOutputStream output = new ByteArrayOutputStream();
bucketObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
bucketObject.executeAndDownloadTo(output);

System.out.println(output.toString());

你在「bucket」和「bucketObjectName」的值會因因素而異 你要存取的 API 部分請參閱關於命名的 命名慣例

C#

以下範例使用 .NET 專用的 Google API 用戶端程式庫,可讓您輕鬆存取儲存在 Google Cloud Storage 中的資料。

您必須先設定要在與 API 通訊時要使用的憑證,以取得資料存取權的授權。藉此建立 AssertionFlowClient 物件,並使用服務帳戶的 developer.gserviceaccount.com 電子郵件地址做為 ServiceAccountId,並在建立服務帳戶時,載入從 Google API 控制台下載的私密金鑰檔案。

string keyPath = @"...-privatekey.p12";
X509Certificate2 certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
    ServiceAccountId = "...@developer.gserviceaccount.com",
    Scope = StorageService.Scopes.DevstorageRead_only.GetStringValue()
};

建立 AssertionFlowClient 物件後,您就能使用該物件將新的 OAuth2Authenticator 物件例項化,可用於將新的 Storage 例項例項化,以便用於 Google Cloud Storage API 的所有要求:

var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
StorageService service = new StorageService(auth);

現在您已建立新的 Storage 物件,可以開始發出要求 至 API您在此提出擷取特定項目的要求 bucketObjectName,來自值區 bucket。我們使用標準 處理 HTTP 下載作業的 .NET 用戶端程式庫類別 Google Cloud Storage,但您必須手動處理 透過重新導向來確保始終是正確的 Authorization 要求中的標頭:

var results = service.Objects.Get(bucketName, bucketObjectName).Fetch();

HttpWebRequest request = createRequest(results.Media.Link, auth);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// Handle redirects manually to ensure that the Authorization header is present if
// your request is redirected.
if (response.StatusCode == HttpStatusCode.TemporaryRedirect)
{
    request = createRequest(response.Headers["Location"], auth);
    response = (HttpWebResponse)request.GetResponse();
}

接著可以從 HttpWebResponse 物件讀取回應的內容 透過 GetResponseStream 照常傳送。您在「bucket」和 bucketObjectName 會因存取的 API 部分而異。請參閱有關命名慣例的章節。

附錄:完整樣本

Java

/*
 * Copyright (c) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.bidmanager.api.samples;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.Storage.Objects.Get;
import com.google.api.services.storage.StorageScopes;

/**
 * A simple class that demonstrates how to download a specific object from a bucket using a
 * service account
 */
public class ServiceDownload {

  /**
   * This is the HTTP Transport object used for automatically refreshing access tokens.
   */
  static final NetHttpTransport HTTP_TRANSPORT = new NetHttpTransport();

  /**
   * This is the JSON factory used for parsing refresh token responses.Your first requirement
   */
  static final JacksonFactory JSON_FACTORY = new JacksonFactory();

  /**
   * The main method will attempt to download a specific named object from the gdbm-public bucket
   * using a service account.
   *
   * @param args Not used.
   */
  public static void main(String[] args) {

    try {
      // Prompt the user for the details of the object to download.
      System.out.print("Name of object to download, e.g. entity/20130430.0.Browser.json:");
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      String bucketObjectName = in.readLine();
      in.close();
      String bucketName = "gdbm-public";

      Credential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
           .setJsonFactory(JSON_FACTORY)
           .setServiceAccountId("...@developer.gserviceaccount.com")
           .setServiceAccountScopes(StorageScopes.DEVSTORAGE_READ_ONLY)
           .setServiceAccountPrivateKeyFromP12File(
               new File("...-privatekey.p12"))
           .build();

      Storage storage = new Storage(HTTP_TRANSPORT, JSON_FACTORY, credential);

      Get bucketObject = storage.objects().get(bucketName, bucketObjectName);

      ByteArrayOutputStream output = new ByteArrayOutputStream();
      bucketObject.getMediaHttpDownloader().setDirectDownloadEnabled(true);
      bucketObject.executeAndDownloadTo(output);
      System.out.println(output.toString());

    } catch (Exception e) {
      System.err.println("Unexpected exception caught: " + e.getMessage());
      e.printStackTrace();
    }

  }


}

C#

/*
 * Copyright (c) 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;

using DotNetOpenAuth.OAuth2;

using Google.Apis;
using Google.Apis.Requests;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Storage.v1beta1;
using Google.Apis.Storage.v1beta1.Data;
using Google.Apis.Util;

namespace ApiSamples
{
    /// <summary>
    /// A simple class that demonstrates how to download a specific object from a bucket using a
    /// service account
    /// </summary>
    class ServiceDownload
    {
        /// <summary>
        /// The main method will attempt to download a specific named object from the
        /// gdbm-public bucket using a service account.
        /// </summary>
        /// <param name="args">Not used.</param>
        public static void Main(string[] args)
        {

            // Prompt the user for the details of the object to download
            Console.WriteLine("Name of object to download, e.g. entity/20130430.0.Browser.json:");
            string bucketObjectName = Console.ReadLine();
            string bucketName = "gdbm-public";

            try
            {
                string keyPath = @"...-privatekey.p12";
                X509Certificate2 certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);
                var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
                {
                    ServiceAccountId = "...@developer.gserviceaccount.com",
                    Scope = StorageService.Scopes.DevstorageRead_only.GetStringValue()
                };
                var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);

                StorageService service = new StorageService(auth);
                var results = service.Objects.Get(bucketName, bucketObjectName).Fetch();

                HttpWebRequest request = createRequest(results.Media.Link, auth);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                // Handle redirects manully to ensure that the Authorization header is present if
                // our request is redirected.
                if (response.StatusCode == HttpStatusCode.TemporaryRedirect)
                {
                    request = createRequest(response.Headers["Location"], auth);
                    response = (HttpWebResponse)request.GetResponse();
                }

                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);
                String data = reader.ReadToEnd();
                Console.Write(data);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception caught: " + e.Message);
                Console.Write(e.StackTrace);
            }
            Console.ReadKey();
        }

        /// <summary>
        /// Generate a HttpWebRequest for the given URL with the appropriate OAuth2 authorization
        /// header applied.  The HttpWebRequest object returned has its AllowAutoRedirect option
        /// disabled to allow us to manually handle redirects.
        /// </summary>
        /// <param name="url">URL that is to be requested with this object</param>
        /// <param name="auth">The OAuth2Authenticator instance that contains the appropriate keys.</param>
        /// <returns>HttpWebRequest object ready to be used to make requests to the API</returns>
        private static HttpWebRequest createRequest(string url, OAuth2Authenticator<AssertionFlowClient> auth)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Headers.Add("Authorization", "Bearer " + auth.State.AccessToken);
            request.AllowAutoRedirect = false;
            return request;
        }

    }
}