设置用户代理

在 BigQuery 客户端上设置自定义用户代理。

代码示例

Java

试用此示例之前,请按照 BigQuery 快速入门:使用客户端库中的 Java 设置说明进行操作。如需了解详情,请参阅 BigQuery Java API 参考文档

如需向 BigQuery 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

import com.google.api.gax.rpc.FixedHeaderProvider;
import com.google.api.gax.rpc.HeaderProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;

public class SetUserAgent {

  private static final String USER_AGENT_HEADER = "user-agent";

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String customUserAgentValue = "my-custom-user-agent-value";
    setUserAgent(projectId, customUserAgentValue);
  }

  public static void setUserAgent(String projectId, String customUserAgentValue)
      throws IOException {
    // Setup the credentials
    GoogleCredentials googleCredentials = GoogleCredentials.getApplicationDefault();

    // Initialize the HeaderProvider object with custom user agent value
    HeaderProvider headerProvider =
        FixedHeaderProvider.create(ImmutableMap.of(USER_AGENT_HEADER, customUserAgentValue));

    // 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()
            .setProjectId(projectId)
            .setCredentials(googleCredentials)
            .setHeaderProvider(headerProvider)
            .build()
            .getService();

    System.out.println(bigQuery.getOptions().getUserAgent());
  }
}

Node.js

试用此示例之前,请按照 BigQuery 快速入门:使用客户端库中的 Node.js 设置说明进行操作。如需了解详情,请参阅 BigQuery Node.js API 参考文档

如需向 BigQuery 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为客户端库设置身份验证

// Import the Google Cloud client library
const {BigQuery} = require('@google-cloud/bigquery');
// Create a client and set the user agent
const bigquery = new BigQuery({userAgent: 'my-user-agent'});

console.log('User agent:');
console.log(bigquery.providedUserAgent);

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器