ITKeyword,专注技术干货聚合推荐

注册 | 登录

解决Error "401 Unauthorized" to upload video in my youtube account with Simple Access API (API Key)

itPublisher 分享于

2020腾讯云10周年活动,优惠非常大!(领取2860元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1040

2020阿里云最低价产品入口,含代金券(新老用户有优惠),
地址https://www.aliyun.com/minisite/goods

I'm trying to upload video in my youtube account with Simple Access API (API Key).

I'm getting this exception.

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)

What is wrong?

Documentation to use Simple Access API (API Key) with youtube-API is very poor. Could anyone help me?

My Simple Access 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 

This is my code.

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
|
  this question
asked Feb 14 '14 at 0:37 gilbertoastolfi 8 4

 | 

1 Answers
1

解决方法

As you can see in the snippet you posted, the simple access API key is designed to identify your project (i.e. for the sake of quotas) when you do not need to access user data. Uploading a video into an account is a form of accessing user data, so you'll need to use oauth2, request the scope 'https://www.googleapis.com/auth/youtube.upload,' and then perform the upload with the access token.

Once you have that oauth2 flow running and your user grants access to the scope, it seems that the rest of your code looks right (but I'm not a Java expert so don't hold me to that!)


|
  this answer
answered Feb 14 '14 at 2:22 jlmcdonald 9,294 2 24 41      Thanks jlmcdonald... I would like the user of my site to upload a video into my youtube account. My web site authenticate in my youtube account and sends the user's video (ie no credentials of my final user). Is possible? –  gilbertoastolfi Feb 14 '14 at 5:05      No; users need to upload into their own accounts, not into yours. Your site should use oAuth2 to authenticate them with their account. Another possibility is to use YouTube Lite; they'll still upload into their own accounts, but it will also make an automatic playlist in your account based on all the videos. –  jlmcdonald Feb 23 '14 at 4:24

 | 


相关阅读排行


相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱

如果您没有收到激活邮件,请注意检查垃圾箱。