Примеры кода Java

Следующие примеры кода, использующие клиентскую библиотеку Google API для Java , доступны для YouTube Content ID API .

Примечание: В этих примерах используется сервис YouTubePartner из com.google.apis:google-api-services-youtubePartner . Для загрузки сгенерированных привязок API идентификаторов контента YouTube, необходимых для запуска этих примеров, см. документацию по клиентским библиотекам.

Получить доступ к каналам, управляемым владельцем контента.

В приведенном ниже примере кода вызывается метод channels.list из API данных YouTube для получения списка каналов, управляемых владельцем контента, отправившим запрос к API.

/*
 * Copyright (c) 2026 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.api.services.samples.youtube.cmdline.partner;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtubePartner.YouTubePartner;
import com.google.api.services.youtubePartner.model.ContentOwnerListResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * This sample retrieves a list of channels managed by the content owner
 * associated with the currently authenticated user's account.
 */
public class MyManagedChannels {

    private static YouTube youtube;
    private static YouTubePartner youtubePartner;

    public static void main(String[] args) {
        List<String> scopes = Arrays.asList(
                "https://www.googleapis.com/auth/youtube.readonly",
                "https://www.googleapis.com/auth/youtubepartner");

        try {
            Credential credential = Auth.authorize(scopes, "mymanagedchannels");

            youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                    .setApplicationName("youtube-cmdline-mymanagedchannels-sample")
                    .build();

            youtubePartner = new YouTubePartner.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                    .setApplicationName("youtube-cmdline-mymanagedchannels-sample")
                    .build();

            String contentOwnerId = getContentOwnerId(youtubePartner);
            listManagedChannels(youtube, contentOwnerId);

        } catch (GoogleJsonResponseException e) {
            System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode()
                    + " : " + e.getDetails().getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IOException: " + e.getMessage());
            e.printStackTrace();
        } catch (Throwable t) {
            System.err.println("Throwable: " + t.getMessage());
            t.printStackTrace();
        }
    }

    /**
     * Calls the contentOwners.list method to retrieve the ID of the content
     * owner associated with the currently authenticated user's account.
     */
    private static String getContentOwnerId(YouTubePartner youtubePartner) throws IOException {
        ContentOwnerListResponse response = youtubePartner.contentOwners()
                .list()
                .setFetchMine(true)
                .execute();
        return response.getItems().get(0).getId();
    }

    /**
     * Retrieves and prints a list of channels that the content owner manages.
     */
    private static void listManagedChannels(YouTube youtube, String contentOwnerId)
            throws IOException {
        System.out.println("Channels managed by content owner '" + contentOwnerId + "':");

        YouTube.Channels.List request = youtube.channels()
                .list("snippet")
                .setOnBehalfOfContentOwner(contentOwnerId)
                .setManagedByMe(true)
                .setMaxResults(50L);

        String nextPageToken = "";
        do {
            request.setPageToken(nextPageToken);
            ChannelListResponse response = request.execute();

            List<Channel> channels = response.getItems();
            if (channels != null) {
                for (Channel channel : channels) {
                    String title = channel.getSnippet().getTitle();
                    String id = channel.getId();
                    System.out.println("  " + title + " (" + id + ")");
                }
            }
            nextPageToken = response.getNextPageToken();
        } while (nextPageToken != null);
    }
}

Создавайте, управляйте и используйте метки активов.

Приведённый ниже пример кода выполняет ряд вызовов API, демонстрирующих, как создавать и использовать метки ресурсов для категоризации и поиска элементов в вашей библиотеке ресурсов.

/*
 * Copyright (c) 2026 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.api.services.samples.youtube.cmdline.partner;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtubePartner.YouTubePartner;
import com.google.api.services.youtubePartner.model.Asset;
import com.google.api.services.youtubePartner.model.AssetLabel;
import com.google.api.services.youtubePartner.model.AssetLabelListResponse;
import com.google.api.services.youtubePartner.model.AssetSearchResponse;
import com.google.api.services.youtubePartner.model.AssetSnippet;
import com.google.api.services.youtubePartner.model.ContentOwnerListResponse;
import com.google.api.services.youtubePartner.model.Metadata;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * This sample demonstrates how to create and use asset labels to categorize
 * and search for items in your asset library.
 */
public class AssetLabels {

    private static YouTubePartner youtubePartner;

    public static void main(String[] args) {
        List<String> scopes = Arrays.asList(
                "https://www.googleapis.com/auth/youtube",
                "https://www.googleapis.com/auth/youtubepartner");

        try {
            Credential credential = Auth.authorize(scopes, "assetlabels");

            youtubePartner = new YouTubePartner.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                    .setApplicationName("youtube-cmdline-assetlabels-sample")
                    .build();

            String