【问题标题】:Error "401 Unauthorized" to upload video in my youtube account with Simple Access API (API Key)使用 Simple Access API(API 密钥)在我的 youtube 帐户中上传视频时出现错误“401 Unauthorized”
【发布时间】:2014-02-14 00:37:11
【问题描述】:

我正在尝试使用 Simple Access API(API 密钥)在我的 youtube 帐户中上传视频。

我遇到了这个异常。

You chose src/resources/video.avi to upload.
Initiation Started
Initiation Completed
Exception: 401 Unauthorized 
com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:143)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:115)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:421)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:340)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:458)
at com.google.api.services.samples.YoutubeSample.queryGoogleYouTube(YoutubeSample.java:126)
at com.google.api.services.samples.YoutubeSample.main(YoutubeSample.java:152)

怎么了?

使用简单访问 API(API 密钥)和 youtube-API 的文档非常差。 谁能帮帮我?

我的简单访问 API:

Simple API Access

Use API keys to identify your project when you do not need to access user data.

Key for server apps (with IP locking)
API key:   AIzaSxxxxxxxxxxxxxxxxxxxxxxx-bVE8jRlzXY
IPs:   Any IP allowed
Activated on:   Feb 11, 2014 7:50 PM
Activated by:   myaccount@gmail.com – you 

这是我的代码。

package com.google.api.services.samples;

import com.google.api.client.googleapis.media.MediaHttpUploader;
import com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.YouTubeRequestInitializer;
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 java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class YoutubeSample {

    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    private static final JsonFactory JSON_FACTORY = new JacksonFactory();

private static YouTube youtube;

private static String VIDEO_FILE_FORMAT = "video/*";

private static final String APPLICATION_NAME = "YoutubeTest";

//Simple API Access
//Use API keys to identify your project when you do not need to access user data.
//Key for server apps (with IP locking) 
private static final String API_KEY = "AIzaSxxxxxxxxxxxxxxxxxx-bVE8jRlzXY"; // This has changed. 

private static File getVideoFromUser() throws IOException {
    return new File("src/resources/video.avi");
}

private static void queryGoogleYouTube() throws Exception {

    ClientCredentials.errorIfNotSpecified();

    try {

//In this piece of code that is my difficulty           
youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY,
                new HttpRequestInitializer() {
                    public void initialize(HttpRequest request)
                            throws IOException {
                    }
                })
                .setApplicationName(APPLICATION_NAME)
                .setYouTubeRequestInitializer(new YouTubeRequestInitializer(API_KEY)).build();

        File videoFile = getVideoFromUser();
        System.out.println("You chose " + videoFile + " to upload.");

        Video videoObjectDefiningMetadata = new Video();

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

        VideoSnippet snippet = new VideoSnippet();

        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription("Video uploaded via YouTube Data API V3 using the Java library "
                + "on " + cal.getTime());

        // Set your keywords.
        List<String> tags = new ArrayList<String>();
        tags.add("test");
        tags.add("example");
        tags.add("java");
        tags.add("YouTube Data API V3");
        tags.add("erase me");
        snippet.setTags(tags);

        videoObjectDefiningMetadata.setSnippet(snippet);

        InputStreamContent mediaContent = new InputStreamContent(
                VIDEO_FILE_FORMAT, new BufferedInputStream(
                        new FileInputStream(videoFile)));
        mediaContent.setLength(videoFile.length());

        YouTube.Videos.Insert videoInsert = youtube.videos().insert(
                "snippet,statistics,status", videoObjectDefiningMetadata,
                mediaContent);

        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();

        uploader.setDirectUploadEnabled(false);

        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader)
                    throws IOException {
                switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                    System.out.println("Initiation Started");
                    break;
                case INITIATION_COMPLETE:
                    System.out.println("Initiation Completed");
                    break;
                case MEDIA_IN_PROGRESS:
                    System.out.println("Upload in progress");
                    System.out.println("Upload percentage: "
                            + uploader.getProgress());
                    break;
                case MEDIA_COMPLETE:
                    System.out.println("Upload Completed!");
                    break;
                case NOT_STARTED:
                    System.out.println("Upload Not Started!");
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);

        // Execute upload.
        Video returnedVideo = videoInsert.execute();

        // Print out returned results.
        System.out
                .println("\n================== Returned Video ==================\n");
        System.out.println("  - Id: " + returnedVideo.getId());
        System.out.println("  - Title: "
                + returnedVideo.getSnippet().getTitle());
        System.out.println("  - Tags: "
                + returnedVideo.getSnippet().getTags());
        System.out.println("  - Privacy Status: "
                + returnedVideo.getStatus().getPrivacyStatus());
        System.out.println("  - Video Count: "
                + returnedVideo.getStatistics().getViewCount());

    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

public static void main(String[] args) {
    try {
        queryGoogleYouTube();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

【问题讨论】:

    标签: youtube youtube-api


    【解决方案1】:

    正如您在发布的 sn-p 中看到的,简单访问 API 密钥旨在在您不需要访问用户数据时识别您的项目(即为了配额) .将视频上传到帐户是访问用户数据的一种形式,因此您需要使用 oauth2,请求范围“https://www.googleapis.com/auth/youtube.upload”,然后使用访问令牌执行上传。

    一旦您运行了该 oauth2 流程并且您的用户授予了对该范围的访问权限,您的其余代码似乎看起来正确(但我不是 Java 专家,所以不要强迫我这样做!)

    【讨论】:

    • 谢谢 jlmcdonald... 我希望我网站的用户将视频上传到我的 youtube 帐户。我的网站在我的 youtube 帐户中进行身份验证并发送用户的视频(即没有我的最终用户的凭据)。有可能吗?
    • 否;用户需要上传到他们自己的帐户,而不是您的帐户。您的站点应该使用 oAuth2 来使用他们的帐户对他们进行身份验证。另一种可能性是使用 YouTube Lite;他们仍会上传到他们自己的帐户,但它还会根据所有视频在您的帐户中创建一个自动播放列表。
    猜你喜欢
    • 2014-10-02
    • 2020-11-12
    • 2015-12-28
    • 2012-11-23
    • 2016-11-28
    • 1970-01-01
    • 2011-09-11
    • 2011-05-14
    • 1970-01-01
    相关资源
    最近更新 更多