Bắt đầu với Cloud Storage

Google Display & Video 360 tự động lưu trữ Entity Read Files trong Google Cloud Storage. Chỉ các tài khoản đã được cấp quyền truy cập mới có thể truy cập vào các tệp này.

Tạo dự án

Tạo và định cấu hình dự án như sau:

  1. Truy cập trang API được bật Bảng điều khiển API của Google.

    Nếu chưa đăng nhập vào Google, bạn sẽ được nhắc đăng nhập.

  2. Trên trình đơn thả xuống cho dự án, hãy chọn một dự án hiện có hoặc tạo dự án mới.
    • Nếu bạn hiện có nhiều dự án, hãy nhớ chọn dự án mà bạn muốn kích hoạt Google Cloud Storage, sau đó chọn Tiếp tục.
    • Hoặc nếu bạn chưa có dự án, hãy chọn Tạo dự án mới, nhập tên Dự án, sau đó chọn Tạo.

      Lưu ý: Bạn nên lưu ý rằng một số giá trị nhận dạng tài nguyên (chẳng hạn như mã dự án) có thể được giữ lại trong suốt thời gian hoạt động của dự án. Vì lý do này, bạn nên tránh lưu trữ thông tin nhạy cảm trong giá trị nhận dạng tài nguyên.

  3. Trong danh sách API đã bật, hãy đảm bảo thành phần Google Cloud Storage có trong danh sách. Nếu thành phần này không có trong danh sách, hãy nhấp vào thẻ Google APIs, tìm và chọn thành phần Google Cloud Storage rồi nhấp vào Enable API (Bật API).

    Lưu ý rằng đối với hầu hết dự án, thành phần Google Cloud Storage đã được bật. Nếu định truy cập vào Google Cloud Storage bằng JSON API, bạn cũng nên xác minh rằng bạn đã bật API JSON của Google Cloud Storage.

  4. Bật tính năng thanh toán cho dự án.

    Để có thể sử dụng Google Cloud Storage, bạn cần bật tính năng thanh toán cho dự án của mình nếu bạn chưa bật. Việc bật tính năng thanh toán không nhất thiết có nghĩa là bạn sẽ bị tính phí. Để biết thêm thông tin, hãy xem phần Giá.

    1. Vẫn trong dự án bộ nhớ trên đám mây, hãy nhấp vào trình đơn thư viện ở góc trên bên trái, rồi chọn Thanh toán.
    2. Nếu bạn chưa có tài khoản thanh toán, hãy làm theo hướng dẫn để tạo một tài khoản thanh toán mới.
    3. Nếu bạn đã có tài khoản thanh toán hiện có, hãy chọn tài khoản đó rồi chọn Đặt tài khoản.

Trong Google API Console, hãy ở trong cùng một dự án và chuyển đến phần tiếp theo.

Thiết lập quyền truy cập vào Cloud Storage

  1. Vẫn trong Bảng điều khiển API của Google trong dự án được yêu cầu, nhấp vào trình đơn thư viện ở góc trên bên trái, chọn API và dịch vụ, sau đó nhấp vào Thông tin xác thực. Trên trang Thông tin xác thực, hãy tìm Khoá tài khoản dịch vụ.

    Tìm địa chỉ email chứa khoá tài khoản dịch vụ:

    1. Chọn đường liên kết Quản lý tài khoản dịch vụ (ở bên phải phần Khoá tài khoản dịch vụ).
    2. Bạn có thể xem địa chỉ email trên trang Quyền hiện ra.

    Nếu không có khoá tài khoản Dịch vụ, hãy tạo một Tài khoản dịch vụ mới:

    1. Chọn trình đơn thả xuống Tạo thông tin xác thực, sau đó chọn Khoá tài khoản dịch vụ.
    2. Trong trình đơn thả xuống Tài khoản dịch vụ, hãy chọn Tài khoản dịch vụ mới.
    3. Nhập Tên cho tài khoản dịch vụ. Mã tài khoản dịch vụ được tạo tự động từ tên và tên dự án.
    4. Ghi lại mã tài khoản dịch vụ gserviceaccount.com địa chỉ email. Mã này không hiển thị trên trang Thông tin xác thực sau khi bạn chọn Tạo.
    5. Trong phần Key type (Loại khoá), hãy chọn JSON.
    6. Nhấp vào Tạo. Tệp JSON có cặp khoá công khai/riêng tư của tài khoản sẽ được lưu vào thư mục Downloads (Tệp đã tải xuống). Khoá này dùng để xác thực ứng dụng của bạn với API và ký tất cả các yêu cầu mà ứng dụng gửi tới API. Lưu trữ tệp JSON đã tạo ở một nơi an toàn, nơi ứng dụng của bạn có thể truy cập vào tệp.
  2. Hãy liên hệ với Nhóm hỗ trợ Display & Video 360 để yêu cầu bật các tệp Đọc thực thể và/hoặc API Trình quản lý giá thầu của Google.

    Sau khi Nhóm hỗ trợ xác nhận quyền truy cập, hãy tạo một Nhóm Google (hoặc các nhóm) riêng và cập nhật các trường sau trong thông tin chi tiết về đối tác Display & Video 360 (lưu ý rằng chỉ những người dùng có quyền truy cập cấp đối tác mới có thể cập nhật):

    • Ghi nhật ký đọc trên Google Group
      Nhóm chỉ có thể đọc chỉ có quyền đọc tệp và liệt kê nội dung của bộ chứa lưu trữ.
    • Quản lý nhật ký trên Google Group
      Nhóm quản lý có tất cả các quyền của nhóm chỉ đọc nhưng cũng có thể thay đổi các ACL của tệp trong bộ chứa. Lưu ý rằng ngay cả nhóm quản lý cũng không có quyền thay đổi các ACL của nhóm, cũng như không có quyền tạo, sửa đổi hoặc xoá tệp.

    Sau khi thêm Nhóm Google, bạn có thể thêm người dùng vào Nhóm Google và xoá người dùng khỏi Nhóm Google theo yêu cầu mà không cần sự tham gia của nhóm hỗ trợ Display & Video 360; chỉ những người dùng trong nhóm của bạn mới có quyền truy cập dữ liệu của bạn.

Truy cập dữ liệu của bạn

Truy cập dữ liệu bằng gsutil

Công cụ gsutil là một ứng dụng dòng lệnh cho phép bạn dễ dàng truy cập dữ liệu Google Cloud Storage của bạn mà không cần lập trình. Ví dụ: bạn có thể sử dụng gsutil như một phần của tập lệnh hoặc tệp hàng loạt thay vì tạo các ứng dụng tùy chỉnh.

Để bắt đầu sử dụng gsutil, hãy đọc tài liệu gsutil. Bạn vẫn cần xác thực bằng OAuth 2 như trước, nhưng chính gsutil sẽ nhắc bạn cung cấp thông tin xác thực vào lần đầu bạn sử dụng và sau đó lưu trữ thông tin đó để sử dụng sau này.

Truy cập dữ liệu theo phương thức lập trình

Google Cloud Storage có các API cho nhiều ngôn ngữ lập trình, cho phép bạn truy cập vào dữ liệu của mình theo cách có lập trình. Mẫu bên dưới hướng dẫn cách tải xuống đơn giản một trong các tệp đọc thực thể từ Google Cloud Storage. Xin lưu ý rằng chỉ Tệp đã đọc đối tượng công khai mới được lưu trữ trong bộ chứa gdbm-public; Tệp đã đọc đối tượng riêng tư của bạn sẽ được lưu trữ trong bộ chứa dành riêng cho đối tác và nhà quảng cáo.

Java

Ví dụ sau đây sử dụng Thư viện ứng dụng API của Google cho Java, giúp bạn dễ dàng truy cập vào dữ liệu được lưu giữ trong Google Cloud Storage. Ngoài Thư viện ứng dụng API chính của Google, bạn cũng cần tải thư viện riêng cho API Cloud Storage xuống.

Trước tiên, bạn cần thiết lập thông tin xác thực sẽ dùng khi giao tiếp với API để được phép truy cập vào dữ liệu của bạn. Bạn có thể thực hiện việc này bằng cách tạo một đối tượng Credential sử dụng địa chỉ email developer.gserviceaccount.com của Tài khoản dịch vụ làm ServiceAccountId, đồng thời tải tệp khoá riêng tư được tải xuống từ Google API Console khi tạo Tài khoản dịch vụ. Việc này sẽ đảm bảo rằng tất cả các yêu cầu sau này gửi đến API đều được ký bằng khoá riêng tư của Tài khoản dịch vụ:

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();

Sau khi tạo đối tượng Credential, bạn có thể sử dụng đối tượng này để tạo thực thể cho đối tượng Storage mới mà bạn có thể sử dụng cho mọi yêu cầu sau này đối với API Google Cloud Storage:

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

Bây giờ, khi đã có đối tượng Storage mới, bạn có thể bắt đầu gửi yêu cầu đến API. Ở đây, bạn đang đưa ra yêu cầu truy xuất một mục cụ thể bucketObjectName từ bộ chứa bucket. Thư viện này sẽ xử lý việc tải tệp xuống qua HTTP từ Google Cloud Storage, sau đó bạn chỉ cần in nội dung ra bảng điều khiển:

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

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

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

Giá trị của bạn cho bucketbucketObjectName sẽ thay đổi tuỳ thuộc vào phần của API bạn đang truy cập; hãy tham khảo phần thích hợp về quy ước đặt tên.

C#

Ví dụ sau đây sử dụng Thư viện ứng dụng API của Google dành cho .NET, giúp đơn giản và dễ dàng truy cập vào dữ liệu được lưu giữ trong Google Cloud Storage.

Trước tiên, bạn cần thiết lập thông tin xác thực sẽ dùng khi giao tiếp với API để được phép truy cập vào dữ liệu của bạn. Bạn có thể thực hiện việc này bằng cách tạo một đối tượng AssertionFlowClient sử dụng địa chỉ email developer.gserviceaccount.com của Tài khoản dịch vụ làm ServiceAccountId, đồng thời tải tệp khoá riêng tư đã tải xuống từ Bảng điều khiển API của Google khi tạo Tài khoản dịch vụ.

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()
};

Sau khi tạo đối tượng AssertionFlowClient, bạn có thể sử dụng đối tượng này để tạo thực thể cho đối tượng OAuth2Authenticator mới mà bạn có thể dùng để tạo thực thể Storage mới cho tất cả các yêu cầu sau này đến API Google Cloud Storage:

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

Bây giờ, khi đã có đối tượng Storage mới, bạn có thể bắt đầu gửi yêu cầu đến API. Ở đây, bạn đang đưa ra yêu cầu truy xuất một mục cụ thể, bucketObjectName, từ bộ chứa bucket. Chúng tôi sử dụng các lớp thư viện ứng dụng .NET tiêu chuẩn để xử lý quá trình tải HTTP xuống từ Google Cloud Storage. Tuy nhiên, bạn phải tự xử lý trường hợp có lệnh chuyển hướng để đảm bảo rằng luôn có tiêu đề Authorization chính xác trong yêu cầu:

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();
}

Sau đó, bạn có thể đọc nội dung của phản hồi từ đối tượng HttpWebResponse thông qua GetResponseStream như bình thường. Giá trị của bạn cho bucketbucketObjectName sẽ thay đổi tuỳ thuộc vào phần của API mà bạn đang truy cập; hãy tham khảo phần thích hợp về quy ước đặt tên.

Phụ lục: Các mẫu hoàn chỉnh

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;
        }

    }
}