開始使用 Cloud Storage

Google Display & Video 360 會自動將實體讀取檔案儲存在 Google Cloud Storage 中。只有已取得存取權的帳戶才能存取這些檔案。

建立專案

請按照下列步驟建立及設定專案:

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

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

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

      注意:專案生命週期結束後,部分資源 ID (例如專案 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. 啟用專案的計費功能。

    使用 Google Cloud Storage 前,如果您尚未啟用專案的計費功能,請先完成這項操作。啟用帳單功能並不一定表示會產生費用。詳情請參閱「定價」。

    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. 請與 Display & Video 360 支援團隊聯絡,要求啟用實體讀取檔案 和/或 Google Bid Manager API。

    支援團隊確認存取權後,請建立專屬的 Google 群組 (或群組),並在 Display & Video 360 夥伴詳細資料中更新下列欄位 (請注意,只有具備夥伴層級存取權的使用者才能執行這類更新):

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

    新增 Google 群組後,您就可以視需要在 Google 群組中新增或移除使用者,不需要另外與 Display & Video 360 支援團隊進行後續合作;只有群組中的使用者才能存取您的資料。

存取你的資料

使用 gsutil 存取資料

gsutil 工具是一種指令列應用程式,可以讓您在沒有程式設計經驗的情況下,輕鬆存取 Google Cloud Storage 資料。舉例來說,您可以使用 gsutil 做為指令碼或批次檔案的一部分,而非建立自訂應用程式。

如要開始使用 gsutil,請參閱 gsutil 說明文件。 您仍必須使用 OAuth 2 進行驗證,但 gsutil 會在您首次使用時提示您提供憑證,並儲存憑證供日後使用。

透過程式輔助方式存取資料

Google Cloud Storage 提供多種程式設計語言的 API,可讓您以程式輔助的方式存取資料。以下範例說明如何從 Google Cloud Storage 下載其中一個實體讀取檔案。請注意,只有公開的實體讀取檔案會儲存在 gdbm-public 值區中;私人 實體讀取檔案會儲存在合作夥伴和廣告客戶專屬的值區中。

Java

下例使用 Java 適用的 Google 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 發出要求了。您在此提出從值區 bucket 擷取特定項目 bucketObjectName 的要求。程式庫會處理 Google Cloud Storage 中檔案的 HTTP 下載作業,然後將內容輸出至控制台:

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

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

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

bucketbucketObjectName 的值會因您存取的 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 物件執行個體化,此物件可用於針對未來所有對 Google Cloud Storage API 發出的要求,將新的 Storage 執行個體執行個體化:

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

現在您已取得新的 Storage 物件,可以開始對 API 發出要求了。您提出了從值區 bucket 擷取特定項目 bucketObjectName 的要求。我們使用標準的 .NET 用戶端程式庫類別來處理來自 Google Cloud Storage 的 HTTP 下載作業,但當要求中有重新導向時,您必須手動處理情況,確保要求中一律使用正確的 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();
}

接著,您可以照常透過 GetResponseStreamHttpWebResponse 物件讀取回應內容。bucketbucketObjectName 的值會因您存取的 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;
        }

    }
}