建立設有範圍的憑證

使用 Drive 和 BigQuery API 範圍建立憑證。

程式碼範例

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 BigQuery 快速入門導覽課程」中的 Java 設定說明操作。詳情請參閱 BigQuery Java API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;

public class AuthDriveScope {

  public static void main(String[] args) throws IOException {
    setAuthDriveScope();
  }

  public static void setAuthDriveScope() throws IOException {
    // Create credentials with Drive & BigQuery API scopes.
    // Both APIs must be enabled for your project before running this code.
    GoogleCredentials credentials =
        ServiceAccountCredentials.getApplicationDefault()
            .createScoped(
                ImmutableSet.of(
                    "https://www.googleapis.com/auth/bigquery",
                    "https://www.googleapis.com/auth/drive"));

    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery =
          BigQueryOptions.newBuilder().setCredentials(credentials).build().getService();

      // Use the client.
      System.out.println("Auth succeeded with multiple scopes. Datasets:");
      for (Dataset dataset : bigquery.listDatasets().iterateAll()) {
        System.out.printf("Dataset: %s%n", dataset.getDatasetId().getDataset());
      }
    } catch (BigQueryException e) {
      System.out.println("Auth failed due to error: \n" + e.toString());
    }
  }
}

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽工具