자바 코드 샘플

YouTube Content ID API에서는 Java용 Google API 클라이언트 라이브러리를 사용하는 다음 코드 샘플을 사용할 수 있습니다.

참고: 이 샘플은 com.google.apis:google-api-services-youtubePartner에서 YouTubePartner 서비스를 가져옵니다. 이 샘플을 실행하는 데 필요한 생성된 YouTube Content ID API 바인딩을 다운로드하려면 클라이언트 라이브러리 문서를 참고하세요.

콘텐츠 소유자가 관리하는 채널 검색

다음 코드 샘플은 YouTube Data API의 channels.list 메서드를 호출하여 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 contentOwnerId = getContentOwnerId(youtubePartner);
            System.out.println("Authenticated as CMS user ID '" + contentOwnerId + "'.");

            String assetLabelName = createAssetLabel(youtubePartner, contentOwnerId, "label1");

            listAssetLabels(youtubePartner, contentOwnerId);

            Asset asset1 = createAsset(youtubePartner, contentOwnerId, "asset1");
            System.out.println("Created new asset ID '" + asset1.getId() + "'.");

            asset1 = updateAsset(youtubePartner, contentOwnerId, asset1,
                    Arrays.asList(assetLabelName, "label3"));
            System.out.println("Added asset labels '" + asset1.getLabel().get(0) + " "
                    + asset1.getLabel().get(1) + "' to '" + asset1.getId() + "'.");

            Asset asset2 = createAsset(youtubePartner, contentOwnerId, "asset2");
            System.out.println("Created new asset ID '" + asset2.getId() + "'.");

            asset2 = updateAsset(youtubePartner, contentOwnerId, asset2,
                    Collections.singletonList("label3"));
            System.out.println("Added asset label '" + asset2.getLabel().get(0) + "' to '"
                    + asset2.getId() + "'.");

            listAssetLabels(youtubePartner, contentOwnerId);

            // AssetSearch may not return expected results immediately due to indexing delay.
            searchAsset(youtubePartner, contentOwnerId, "label1, label3", null);
            searchAsset(youtubePartner, contentOwnerId, "label1, label3", true);

            System.out.println("All done!");

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

    private static String getContentOwnerId(YouTubePartner youtubePartner) throws IOException {
        ContentOwnerListResponse response = youtubePartner.contentOwners()
                .list()
                .setFetchMine(true)
                .execute();
        return response.getItems().get(0).getId();
    }

    private static String createAssetLabel(YouTubePartner youtubePartner, String contentOwnerId,
            String labelName) throws IOException {
        AssetLabel label = new AssetLabel();
        label.setLabelName(labelName);

        try {
            AssetLabel response = youtubePartner.assetLabels()
                    .insert(label)
                    .setOnBehalfOfContentOwner(contentOwnerId)
                    .execute();
            System.out.println("Created new asset label '" + response.getLabelName() + "'.");
            return response.getLabelName();
        } catch (GoogleJsonResponseException e) {
            if (e.getStatusCode() == 409) {
                System.err.println("Asset label '" + labelName + "' already exists.");
                return labelName;
            }
            throw e;
        }
    }

    private static void listAssetLabels(YouTubePartner youtubePartner, String contentOwnerId)
            throws IOException {
        AssetLabelListResponse response = youtubePartner.assetLabels()
                .list()
                .setOnBehalfOfContentOwner(contentOwnerId)
                .execute();

        List<AssetLabel> labels = response.getItems();
        if (labels != null) {
            for (AssetLabel label : labels) {
                System.out.println("Found asset label '" + label.getLabelName() + "'.");
            }
        }
    }

    private static Asset createAsset(YouTubePartner youtubePartner, String contentOwnerId,
            String title) throws IOException {
        Metadata metadata = new Metadata();
        metadata.setTitle(title);

        Asset asset = new Asset();
        asset.setType("web");
        asset.setMetadata(metadata);

        return youtubePartner.assets()
                .insert(asset)
                .setOnBehalfOfContentOwner(contentOwnerId)
                .execute();
    }

    private static Asset updateAsset(YouTubePartner youtubePartner, String contentOwnerId,
            Asset asset, List<String> labels) throws IOException {
        asset.setLabel(labels);

        return youtubePartner.assets()
                .update(asset.getId(), asset)
                .setOnBehalfOfContentOwner(contentOwnerId)
                .execute();
    }

    private static void searchAsset(YouTubePartner youtubePartner, String contentOwnerId,
            String labels, Boolean includeAnyLabel) throws IOException {
        YouTubePartner.AssetSearch.List request = youtubePartner.assetSearch()
                .list()
                .setOnBehalfOfContentOwner(contentOwnerId)
                .setLabels(labels);

        if (includeAnyLabel != null) {
            request.setIncludeAnyProvidedlabel(includeAnyLabel);
        }

        AssetSearchResponse response = request.execute();
        List<AssetSnippet> items = response.getItems();
        if (items != null) {
            for (AssetSnippet snippet : items) {
                System.out.println("Found asset ID '" + snippet.getId() + "'.");
            }
        }
    }
}

저작물 만들기, 동영상 업로드 및 소유권 주장

다음 코드 샘플은 애셋을 만들고 해당 애셋의 소유권을 설정하고, 동영상을 업로드하고, 동영상을 애셋의 일치로 신고하고, 동영상의 광고 옵션을 설정하기 위해 일련의 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.client.googleapis.media.MediaHttpUploader;
import com.google.api.client.http.FileContent;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Video;
import com.google.api.services.youtube.model.VideoSnippet;
import com.google.api.services.youtube.model.VideoStatus;
import com.google.api.services.youtubePartner.YouTubePartner;
import com.google.api.services.youtubePartner.model.Asset;
import com.google.api.services.youtubePartner.model.Claim;
import com.google.api.services.youtubePartner.model.ContentOwnerListResponse;
import com.google.api.services.youtubePartner.model.Metadata;
import com.google.api.services.youtubePartner.model.Policy;
import com.google.api.services.youtubePartner.model.PolicyRule;
import com.google.api.services.youtubePartner.model.RightsOwnership;
import com.google.api.services.youtubePartner.model.TerritoryOwners;
import com.google.api.services.youtubePartner.model.VideoAdvertisingOption;

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

/**
 * This sample creates an asset, sets ownership for that asset, uploads a video
 * to a managed channel, claims the video as a match of the asset, and enables
 * TrueView instream ads for the video.
 */
public class UploadMonetizeVideo {

    private static YouTube youtube;
    private static YouTubePartner youtubePartner;

    private static final String VIDEO_FILE_FORMAT = "video/*";
    private static final String SAMPLE_VIDEO_FILENAME = "sample-video.mp4";
    private static final String MANAGED_CHANNEL_ID = "UC_ENTER_MANAGED_CHANNEL_ID";

    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, "uploadmonetizevideo");

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

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

            String contentOwnerId = getContentOwnerId(youtubePartner);
            System.out.println("Authenticated as content owner ID '" + contentOwnerId + "'.");

            String title = "Test Upload and Claim Title";
            String description = "Test Upload and Claim Description";

            String videoId = uploadVideo(youtube, contentOwnerId, MANAGED_CHANNEL_ID,
                    title, description);
            System.out.println("Successfully uploaded video ID '" + videoId + "'.");

            String assetId = createAsset(youtubePartner, contentOwnerId, title, description);
            System.out.println("Created new asset ID '" + assetId + "'.");

            setAssetOwnership(youtubePartner, contentOwnerId, assetId);
            System.out.println("Successfully set asset ownership.");

            String claimId = claimVideo(youtubePartner, contentOwnerId, assetId, videoId, null);
            System.out.println("Created new claim ID '" + claimId + "'.");

            setAdvertisingOptions(youtubePartner, contentOwnerId, videoId);
            System.out.println("Successfully set advertising options.");

            System.out.println("All done!");

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

    private static String getContentOwnerId(YouTubePartner youtubePartner) throws IOException {
        ContentOwnerListResponse response = youtubePartner.contentOwners()
                .list()
                .setFetchMine(true)
                .execute();
        return response.getItems().get(0).getId();
    }

    private static String uploadVideo(YouTube youtube, String contentOwnerId, String channelId,
            String title, String description) throws IOException {
        Video videoObjectDefiningMetadata = new Video();

        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);

        VideoSnippet snippet = new VideoSnippet();
        snippet.setTitle(title);
        snippet.setDescription(description);
        snippet.setCategoryId("22");
        videoObjectDefiningMetadata.setSnippet(snippet);

        File videoFile = new File(SAMPLE_VIDEO_FILENAME);
        FileContent mediaContent = new FileContent(VIDEO_FILE_FORMAT, videoFile);

        YouTube.Videos.Insert videoInsert = youtube.videos()
                .insert("snippet,status", videoObjectDefiningMetadata, mediaContent)
                .setOnBehalfOfContentOwner(contentOwnerId)
                .setOnBehalfOfContentOwnerChannel(channelId);

        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
        uploader.setDirectUploadEnabled(false);

        Video returnedVideo = videoInsert.execute();
        return returnedVideo.getId();
    }

    private static String createAsset(YouTubePartner youtubePartner, String contentOwnerId,
            String title, String description) throws IOException {
        Metadata metadata = new Metadata();
        metadata.setTitle(title);
        metadata.setDescription(description);

        Asset asset = new Asset();
        asset.setType("web");
        asset.setMetadata(metadata);

        Asset insertedAsset = youtubePartner.assets()
                .insert(asset)
                .setOnBehalfOfContentOwner(contentOwnerId)
                .execute();
        return insertedAsset.getId();
    }

    private static void setAssetOwnership(YouTubePartner youtubePartner, String contentOwnerId,
            String assetId) throws IOException {
        TerritoryOwners territoryOwners = new TerritoryOwners();
        territoryOwners.setOwner(contentOwnerId);
        territoryOwners.setRatio(100.0);
        territoryOwners.setType("exclude");
        territoryOwners.setTerritories(Collections.emptyList());

        RightsOwnership ownership = new RightsOwnership();
        ownership.setGeneral(Collections.singletonList(territoryOwners));

        youtubePartner.ownership()
                .update(assetId, ownership)
                .setOnBehalfOfContentOwner(contentOwnerId)
                .execute();
    }

    private static String claimVideo(YouTubePartner youtubePartner, String contentOwnerId,
            String assetId, String videoId, String policyId) throws IOException {
        Policy policy = new Policy();
        if (policyId != null && !policyId.isEmpty()) {
            policy.setId(policyId);
        } else {
            PolicyRule rule = new PolicyRule();
            rule.setAction("monetize");
            policy.setRules(Collections.singletonList(rule));
        }

        Claim claim = new Claim();
        claim.setAssetId(assetId);
        claim.setVideoId(videoId);
        claim.setPolicy(policy);
        claim.setContentType("audiovisual");

        Claim insertedClaim = youtubePartner.claims()
                .insert(claim)
                .setOnBehalfOfContentOwner(contentOwnerId)
                .execute();
        return insertedClaim.getId();
    }

    private static void setAdvertisingOptions(YouTubePartner youtubePartner, String contentOwnerId,
            String videoId) throws IOException {
        VideoAdvertisingOption advertisingOption = new VideoAdvertisingOption();
        advertisingOption.setAdFormats(Collections.singletonList("trueview_instream"));

        youtubePartner.videoAdvertisingOptions()
                .update(videoId, advertisingOption)
                .setOnBehalfOfContentOwner(contentOwnerId)
                .execute();
    }
}