使用请求者付款

转到概念

本页面介绍如何设置请求者付款功能,并通过相关示例说明如何对启用了请求者付款功能的存储分区发起请求。

设置请求者付款

以下部分介绍如何启用和停用请求者付款功能,以及如何检查存储分区是否启用了请求者付款功能。

前提条件

  1. 您应具有 storage.buckets.get 权限,以便获取存储分区的请求者付款状态。另外,使用 Google Cloud Console 或 gsutil 启用和停用请求者付款功能时也需要该权限。

  2. 启用或停用请求者付款功能时,您必须拥有 storage.buckets.update 权限。

  3. 停用请求者付款功能时,您必须在请求中加入结算项目,或者拥有 resourcemanager.projects.createBillingAssignment 权限。如需了解详情,请参阅请求者付款功能的使用和访问要求

您可以通过角色向用户授予权限。例如,用户授予 Storage Admin 角色具有以上所有 storage.buckets 权限。您可以将角色添加到存储分区所属的项目

启用请求者付款功能

要为存储分区启用请求者付款功能,请按如下所述操作:

控制台

  1. 在 Google Cloud Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,找到要启用的存储分区,然后点击请求者付款列中的关闭按钮。

  3. 在随即显示的窗口中,点击开启

此功能启用后,该存储分区对应的请求者付款列中会显示一个绿色气泡和一个开启按钮。

请参阅问题排查,了解如何获取有关 Cloud Storage 浏览器中失败操作的详细错误信息。

gsutil

使用 gsutil requesterpays set on 命令:

gsutil requesterpays set on gs://BUCKET_NAME

其中 BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetBilling(gcs::BucketBilling{true}));
  if (!metadata) throw std::runtime_error(metadata.status().message());

  std::cout << "Billing configuration for bucket " << metadata->name()
            << " is updated. The bucket now";
  if (!metadata->has_billing()) {
    std::cout << " has no billing configuration.\n";
  } else if (metadata->billing().requester_pays) {
    std::cout << " is configured to charge the caller for requests\n";
  } else {
    std::cout << " is configured to charge the project that owns the bucket"
              << " for requests.\n";
  }
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

void EnableRequesterPays(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        UserProject = s_projectId
    });
    bucket.Billing = bucket.Billing ?? new Bucket.BillingData();
    bucket.Billing.RequesterPays = true;
    bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
        UserProject = s_projectId
    });
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

ctx := context.Background()

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	RequesterPays: true,
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class EnableRequesterPays {
  public static void enableRequesterPays(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    bucket.toBuilder().setRequesterPays(true).build().update();

    System.out.println("Requester pays enabled for bucket " + bucketName);
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function enableRequesterPays() {
  // Enables requester-pays requests
  await storage.bucket(bucketName).enableRequesterPays();

  console.log(
    `Requester-pays requests have been enabled for bucket ${bucketName}.`
  );
}

enableRequesterPays().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Enable a bucket's requesterpays metadata.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function enable_requester_pays($projectId, $bucketName)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'billing' => [
            'requesterPays' => true
        ]
    ]);
    printf('Requester pays has been enabled for %s' . PHP_EOL, $bucketName);
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

from google.cloud import storage

def enable_requester_pays(bucket_name):
    """Enable a bucket's requesterpays metadata"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.requester_pays = True
    bucket.patch()

    print("Requester Pays has been enabled for {}".format(bucket_name))

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name

bucket.requester_pays = true

puts "Requester pays has been enabled for #{bucket_name}"

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件:

    {
      "billing": {
        "requesterPays": true
      }
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API

    curl -X PATCH --data-binary @JSON_FILE_NAME.json \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=billing"

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .xml 文件:

    <BillingConfiguration>
      <RequesterPays>Enabled</RequesterPays>
    </BillingConfiguration>
  3. 使用 cURL,通过 PUT Bucket 请求和 requesterpays 查询字符串参数调用 XML API

    curl -X PUT --data-binary @XML_FILE_NAME.xml \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?billing"

    其中:

    • XML_FILE_NAME 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

停用请求者付款功能

要为存储分区停用请求者付款功能,请按如下所述操作:

控制台

  1. 在 Google Cloud Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,找到要停用的存储分区,然后点击请求者付款列中的开启按钮。

  3. 在随即显示的窗口中,点击关闭

此功能停用后,请求者付款列中会显示一个灰色气泡和一个关闭按钮。

请参阅问题排查,了解如何获取有关 Cloud Storage 浏览器中失败操作的详细错误信息。

gsutil

使用 gsutil requesterpays set off 命令:

gsutil requesterpays set off gs://BUCKET_NAME

其中 BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& billed_project) {
  StatusOr<gcs::BucketMetadata> metadata = client.PatchBucket(
      bucket_name,
      gcs::BucketMetadataPatchBuilder().SetBilling(gcs::BucketBilling{false}),
      gcs::UserProject(billed_project));
  if (!metadata) throw std::runtime_error(metadata.status().message());

  std::cout << "Billing configuration for bucket " << bucket_name
            << " is updated. The bucket now";
  if (!metadata->has_billing()) {
    std::cout << " has no billing configuration.\n";
  } else if (metadata->billing().requester_pays) {
    std::cout << " is configured to charge the caller for requests\n";
  } else {
    std::cout << " is configured to charge the project that owns the bucket"
              << " for requests.\n";
  }
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

void DisableRequesterPays(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        UserProject = s_projectId
    });
    bucket.Billing = bucket.Billing ?? new Bucket.BillingData();
    bucket.Billing.RequesterPays = false;
    bucket = storage.UpdateBucket(bucket, new UpdateBucketOptions()
    {
        // Use IfMetagenerationMatch to avoid race conditions.
        IfMetagenerationMatch = bucket.Metageneration,
        UserProject = s_projectId
    });
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

ctx := context.Background()

bucket := c.Bucket(bucketName)
bucketAttrsToUpdate := storage.BucketAttrsToUpdate{
	RequesterPays: false,
}
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if _, err := bucket.Update(ctx, bucketAttrsToUpdate); err != nil {
	return err
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class DisableRequesterPays {
  public static void disableRequesterPays(String projectId, String bucketName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    bucket.toBuilder().setRequesterPays(false).build().update();

    System.out.println("Requester pays disabled for bucket " + bucketName);
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档


/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function disableRequesterPays() {
  // Disables requester-pays requests
  await storage.bucket(bucketName).disableRequesterPays();

  console.log(
    `Requester-pays requests have been disabled for bucket ${bucketName}.`
  );
}

disableRequesterPays().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Disable a bucket's requesterpays metadata.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function disable_requester_pays($projectId, $bucketName)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $bucket = $storage->bucket($bucketName);
    $bucket->update([
        'billing' => [
            'requesterPays' => false
        ]
    ]);
    printf('Requester pays has been disabled for %s' . PHP_EOL, $bucketName);
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

from google.cloud import storage

def disable_requester_pays(bucket_name):
    """Disable a bucket's requesterpays metadata"""
    # bucket_name = "my-bucket"

    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    bucket.requester_pays = False
    bucket.patch()

    print("Requester Pays has been disabled for {}".format(bucket_name))

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name

bucket.requester_pays = false

puts "Requester pays has been disabled for #{bucket_name}"

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .json 文件:

    {
      "billing": {
        "requesterPays": false
      }
    }
  3. 使用 cURL,通过 PATCH Bucket 请求调用 JSON API

    curl -X PATCH --data-binary @JSON_FILE_NAME.json \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=billing"

    其中:

    • JSON_FILE_NAME 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 创建一个包含以下信息的 .xml 文件:

    <BillingConfiguration>
      <RequesterPays>Disabled</RequesterPays>
    </BillingConfiguration>
  3. 使用 cURL,通过 PUT Bucket 请求和 requesterpays 查询字符串参数调用 XML API

    curl -X PUT --data-binary @XML_FILE_NAME.xml \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?billing"

    其中:

    • XML_FILE_NAME 是您在第 2 步中创建的文件的名称。
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

检查请求者付款功能是否已启用

要检查某个存储分区是否启用了请求者付款功能,请按如下所述操作:

控制台

  1. 在 Google Cloud Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,可在请求者付款列中查看每个存储分区的请求者付款功能状态。

如果已启用,则状态为绿色且显示有文字开启

gsutil

使用 gsutil requesterpays get 命令:

gsutil requesterpays get gs://BUCKET_NAME

其中 BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

如果请求者付款功能已启用,您会看到类似如下所示的响应:

gs://my-bucket: Enabled

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& user_project) {
  StatusOr<gcs::BucketMetadata> metadata =
      client.GetBucketMetadata(bucket_name, gcs::UserProject(user_project));
  if (!metadata) throw std::runtime_error(metadata.status().message());

  if (!metadata->has_billing()) {
    std::cout
        << "The bucket " << metadata->name() << " does not have a"
        << " billing configuration. The default applies, i.e., the project"
        << " that owns the bucket pays for the requests.\n";
    return;
  }

  if (metadata->billing().requester_pays) {
    std::cout
        << "The bucket " << metadata->name()
        << " is configured to charge the calling project for the requests.\n";
  } else {
    std::cout << "The bucket " << metadata->name()
              << " is configured to charge the project that owns the bucket "
                 "for the requests.\n";
  }
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

bool GetRequesterPays(string bucketName)
{
    var storage = StorageClient.Create();
    var bucket = storage.GetBucket(bucketName, new GetBucketOptions()
    {
        UserProject = s_projectId
    });
    bool? requesterPaysOrNull = bucket.Billing?.RequesterPays;
    bool requesterPays =
        requesterPaysOrNull.HasValue ? requesterPaysOrNull.Value : false;
    Console.WriteLine("RequesterPays: {0}", requesterPays);
    return requesterPays;
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

ctx := context.Background()

ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
attrs, err := c.Bucket(bucketName).Attrs(ctx)
if err != nil {
	return err
}
log.Printf("Is requester pays enabled? %v\n", attrs.RequesterPays)

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();

// The name of the bucket to retrieve requester-pays status, eg. "my-bucket"
// String bucketName = "my-bucket"
// Retrieve the bucket, throws StorageException on failure
Bucket bucket = storage.get(bucketName, Storage.BucketGetOption.fields(BucketField.BILLING));

System.out.println("Requester pays status : " + bucket.requesterPays());

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getRequesterPaysStatus() {
  // Gets the requester-pays status of a bucket
  const [metadata] = await storage.bucket(bucketName).getMetadata();

  let status;
  if (metadata && metadata.billing && metadata.billing.requesterPays) {
    status = 'enabled';
  } else {
    status = 'disabled';
  }
  console.log(
    `Requester-pays requests are ${status} for bucket ${bucketName}.`
  );
}

getRequesterPaysStatus().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Get a bucket's requesterpays metadata.
 *
 * @param string $projectId Your Google Cloud project ID.
 * @param string $bucketName Name of your Google Cloud Storage bucket.
 *
 * @return void
 */
function get_requester_pays_status($projectId, $bucketName)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $bucket = $storage->bucket($bucketName);
    $bucketInformation = $bucket->info();
    $requesterPaysStatus = $bucketInformation['billing']['requesterPays'];
    if ($requesterPaysStatus) {
        printf('Requester Pays is enabled for %s' . PHP_EOL, $bucketName);
    } else {
        printf('Requester Pays is disabled for %s' . PHP_EOL, $bucketName);
    }
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

from google.cloud import storage

def get_requester_pays_status(bucket_name):
    """Get a bucket's requester pays metadata"""
    # bucket_name = "my-bucket"
    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    requester_pays_status = bucket.requester_pays

    if requester_pays_status:
        print("Requester Pays is enabled for {}".format(bucket_name))
    else:
        print("Requester Pays is disabled for {}".format(bucket_name))

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

# bucket_name = "Name of your Google Cloud Storage bucket"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name

if bucket.requester_pays
  puts "Requester Pays is enabled for #{bucket_name}"
else
  puts "Requester Pays is disabled for #{bucket_name}"
end

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 GET Bucket 请求调用 JSON API

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=billing"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 GET Bucket 请求和 billing 查询字符串参数调用 XML API

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME?billing"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌的名称。
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket

访问启用了请求者付款功能的存储分区

以下示例显示了如何添加结算项目,以便从启用了请求者付款功能的存储分区中下载对象。若要对启用了请求者付款功能的存储分区或该存储分区中的对象执行其他请求,可以按照与此类似的过程进行操作。请参阅请求者付款功能访问要求,了解前提条件注意事项。

控制台

  1. 在 Google Cloud Console 中打开 Cloud Storage 浏览器。
    打开 Cloud Storage 浏览器
  2. 在存储分区列表中,找到包含要下载的对象的存储分区,并点击其名称。

  3. 在随即出现的窗口中,使用下拉菜单选择结算项目。

  4. 选中相应复选框以确认您有权使用所选项目进行结算。

  5. 点击保存

  6. 按照正常方式下载对象

请参阅问题排查,了解如何获取有关 Cloud Storage 浏览器中失败操作的详细错误信息。

gsutil

在您的请求中使用 -u 标志:

gsutil -u PROJECT_ID cp gs://BUCKET_NAME/OBJECT_NAME OBJECT_DESTINATION

其中:

  • PROJECT_ID 是要结算的项目的 ID, 例如 my-project
  • BUCKET_NAME 是相关存储分区的名称, 例如 my-bucket
  • OBJECT_NAME 是您要下载的对象的名称,例如 pets/dog.png
  • OBJECT_DESTINATION 是您要保存您的对象的位置。例如 Desktop/dog.png

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

namespace gcs = google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& billed_project) {
  gcs::ObjectReadStream stream = client.ReadObject(
      bucket_name, object_name, gcs::UserProject(billed_project));

  std::string line;
  while (std::getline(stream, line, '\n')) {
    std::cout << line << "\n";
  }
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

private void DownloadObjectRequesterPays(string bucketName,
    string objectName, string localPath = null)
{
    var storage = StorageClient.Create();
    localPath = localPath ?? Path.GetFileName(objectName);
    using (var outputFile = File.OpenWrite(localPath))
    {
        storage.DownloadObject(bucketName, objectName, outputFile,
            new DownloadObjectOptions()
            {
                UserProject = s_projectId
            });
    }
    Console.WriteLine(
        $"downloaded {objectName} to {localPath} paid by {s_projectId}.");
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

// downloadUsingRequesterPays downloads an object using billing project.
func downloadUsingRequesterPays(w io.Writer, bucket, object, billingProjectID string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// billingProjectID := "billing_account_id"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %v", err)
	}
	defer client.Close()

	b := client.Bucket(bucket).UserProject(billingProjectID)
	src := b.Object(object)

	// Open local file.
	f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755)
	if err != nil {
		return fmt.Errorf("os.OpenFile: %v", err)
	}

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	rc, err := src.NewReader(ctx)
	if err != nil {
		return fmt.Errorf("Object(%q).NewReader: %v", object, err)
	}
	if _, err := io.Copy(f, rc); err != nil {
		return fmt.Errorf("io.Copy: %v", err)
	}
	if err := rc.Close(); err != nil {
		return fmt.Errorf("Reader.Close: %v", err)
	}
	fmt.Fprintf(w, "Downloaded using %v as billing project.\n", billingProjectID)
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.nio.file.Path;

public class DownloadRequesterPaysObject {
  public static void downloadRequesterPaysObject(
      String projectId, String bucketName, String objectName, Path destFilePath) {
    // The project ID to bill
    // String projectId = "my-billable-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The path to which the file should be downloaded
    // Path destFilePath = Paths.get("/local/path/to/file.txt");

    Storage storage = StorageOptions.getDefaultInstance().getService();
    Blob blob = storage.get(BlobId.of(bucketName, objectName));
    blob.downloadTo(destFilePath, Blob.BlobSourceOption.userProject(projectId));

    System.out.println(
        "Object " + objectName + " downloaded to " + destFilePath + " and billed to " + projectId);
  }
}

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档


/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'The project ID to bill from, e.g. some-project-id';
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const srcFilename = 'Name of file to download, e.g. file.txt';
// const destFilename = 'Local destination of file, e.g. ./local/path/to/file.txt';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function downloadFileUsingRequesterPays() {
  const options = {
    // The path to which the file should be downloaded, e.g. "./file.txt"
    destination: destFilename,

    // The project to bill from, if requester-pays requests are enabled
    userProject: projectId,
  };

  // Downloads the file
  await storage.bucket(bucketName).file(srcFilename).download(options);

  console.log(
    `gs://${bucketName}/${srcFilename} downloaded to ${destFilename} using requester-pays requests.`
  );
}

downloadFileUsingRequesterPays().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Download file using specified project as requester
 *
 * @param string $projectId Your Google Cloud billable project ID.
 * @param string $bucketName A Google Cloud Storage bucket name.
 * @param string $objectName Name of object in Google Cloud Storage to download locally.
 * @param string $destination Path to local file to save.
 *
 * @return void
 */
function download_file_requester_pays($projectId, $bucketName, $objectName, $destination)
{
    $storage = new StorageClient([
        'projectId' => $projectId
    ]);
    $userProject = true;
    $bucket = $storage->bucket($bucketName, $userProject);
    $object = $bucket->object($objectName);
    $object->downloadToFile($destination);
    printf('Downloaded gs://%s/%s to %s using requester-pays requests.' . PHP_EOL,
        $bucketName, $objectName, basename($destination));
}

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

from google.cloud import storage

def download_file_requester_pays(
    bucket_name, project_id, source_blob_name, destination_file_name
):
    """Download file using specified project as the requester"""
    # bucket_name = "your-bucket-name"
    # project_id = "your-project-id"
    # source_blob_name = "source-blob-name"
    # destination_file_name = "local-destination-file-name"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name, user_project=project_id)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)

    print(
        "Blob {} downloaded to {} using a requester-pays request.".format(
            source_blob_name, destination_file_name
        )
    )

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

# bucket_name = "A Google Cloud Storage bucket name"
# file_name   = "Name of file in Google Cloud Storage to download locally"
# local_path  = "Destination path for downloaded file"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name, skip_lookup: true, user_project: true
file    = bucket.file file_name

file.download local_path

puts "Downloaded #{file.name} using billing project #{storage.project}"

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 在您的请求中,加入 userProject 查询字符串参数(已设为要结算的项目的 ID):

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?alt=media&userProject=PROJECT_ID"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • SAVE_TO_LOCATION 是您要保存您的对象的位置。例如 Desktop/dog.png
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket
    • OBJECT_NAME 是您要下载的对象的名称,例如 pets/dog.png
    • PROJECT_ID 是要结算的项目的 ID,例如 my-project

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 在您的请求中,加入 x-goog-user-project 标头(已设为要结算的项目的 ID):

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "x-goog-user-project: PROJECT_ID" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • PROJECT_ID 是要结算的项目的 ID,例如 my-project
    • SAVE_TO_LOCATION 是您要保存您的对象的位置。例如 Desktop/dog.png
    • BUCKET_NAME 是相关存储分区的名称,例如 my-bucket
    • OBJECT_NAME 是您要下载的对象的名称,例如 pets/dog.png

后续步骤