API данных Youtube - HTTP / 1.1 401 Неавторизовано - PullRequest
0 голосов
/ 18 июня 2020

Когда я хочу использовать API данных YouTube для загрузки видео, он генерирует исключение 401, однако мои учетные данные имеют область действия

upload("`https://www.googleapis.com/auth/youtube.upload`").

. Я включил API в консоли разработчика Google. Как это исправить? Я очень запутался.

my api console

мой код

2020-06-18 17: 28: 18.007 INFO 26088 --- [main ] c .google.api.client.http.HttpTransport:

-------------- ЗАПРОС --------------

POST https://accounts.google.com/o/oauth2/token

Accept-Encoding: gzip

User-Agent: Google-HTTP- Java -Client / 1.23.0 (gzip)

Content-Type: application / x- www-form-urlencoded; charset = UTF-8

Content-Length: 269

2020-06-18 17: 28: 18.007 INFO 26088 - - [main] c .google.api.client.http.HttpTransport: curl -v --compressed -X POST -H 'Accept-Encoding: gzip' -H 'User-Agent: Google-HTTP- Java -Client / 1.23.0 (gzip) '-H' Content-Type: application / x- www-form-urlencoded; charset = UTF-8 '-d' @ - '-' https://accounts.google.com/o/oauth2/token '<< $$$ </p>

2020-06-18 17: 28: 18.929 INFO 26088 --- [main] c .google.api.client.http.HttpTransport: Всего: 269 байт

2020-06- 18 17: 28: 18.929 INFO 26088 --- [main] c .google.api.client.http.HttpTransport: grant_type = refresh_token & refres h_token = ... & client_id = ... & client_secret = ...

2020-06-18 17: 28: 19.153 INFO 26088 --- [main] c .google.api.client.http .HttpTransport: -------------- ОТВЕТ --------------

HTTP / 1.1 200 OK

Передача -Кодирование: по частям

Параметры X-Frame: SAMEORIGIN

Alt-Sv c: h3-28 = ": 443"; ma = 2592000, h3-27 = ": 443"; ma = 2592000, h3-25 = ": 443"; ma = 2592000, h3-T050 = ": 443"; ma = 2592000, h3-Q050 = ": 443"; ma = 2592000, h3-Q049 = ": 443"; ma = 2592000, h3-Q048 = ": 443"; ma = 2592000, h3-Q046 = ": 443"; ma = 2592000, h3-Q043 = ": 443"; ma = 2592000, quic = ": 443"; ma = 2592000; v = "46,43"

Cache-Control: частный Сервер: строительные леса на HTTPServer2 Параметры X-Content-Type: nosniff Content-Encoding: gzip Vary: Referer Vary: X-Origin Vary: Origin X- XSS-защита: 0 Дата: чт, 18 июня 2020 г., 09:28:19 GMT Content-Type: application / json; charset = utf-8

2020-06-18 17: 28: 19.175 INFO 26088 --- [main] c .google.api.client.http.HttpTransport: Всего: 585 байт

2020-06-18 17: 28: 19.176 INFO 26088 --- [main] c .google.api.client.http.HttpTransport: {"access_token": "...", "expires_in": 3599, "scope": "https://www.googleapis.com/auth/youtube **https://www.googleapis.com/auth/youtube.upload** https://www.googleapis.com/auth/content https://www.googleapis.com/auth/siteverification https://www.googleapis.com/auth/adwords https://www.googleapis.com/auth/siteverification.verify_only https://www.googleapis.com/auth/manufacturercenter", "token_type": "Bearer"}

2020-06-18 17: 28: 22.490 INFO 26088 --- [main] c .google. api.client.http.HttpTransport: Всего: 144 байта

2020-06-18 17: 28: 22.492 INFO 26088 --- [main] c .google.api.client.http.HttpTransport: {"snippet": {"categoryId": "22", "description": "Описание загруженного видео.", "title": "Тестовая загрузка видео."}, "status": {"privacyStatus": "private" }}

2020-06-18 17: 28: 22.493 INFO 26088 --- [main] c .google.api.client.http.HttpTransport: ---------- ---- ЗАПРОС --------------

POST

https://www.googleapis.com/upload/youtube/v3/videos?access_token=...&part=snippet&part=status&uploadType=resumable

Accept-Encoding: gzip

User-Agent: ADAM Google-API- Java -Client / 1.30.9 Google-HTTP- Java -Client / 1.23.0 (gzip) * 1 063 *

x-goog-api-client: gl-java / 1.8.0 gdcl / 1.30.9 windows -10 / 10.0

x-upload-content-type: application / octet- поток

x-upload-content-length: 4969741

Content-Type: application / json; charset = UTF-8

Кодировка содержимого: gzip

Длина содержимого: 125

2020-06-18 17: 28: 22.494 INFO 26088 --- [main ] c .google.api.client.http.HttpTransport: curl -v --compressed -X POST -H 'Accept-Encoding: gzip' -H 'User-Agent: ADAM Google-API- Java -Client /1.30.9 Google-HTTP- Java -Client / 1.23.0 (gzip) '-H' x-goog-api-client: gl-java / 1.8.0 gdcl / 1.30.9 windows -10 / 10.0 '-H' x-upload-content-type: application / octet-stream '-H' x-upload-content-length: 4969741 '-H' Content-Type: application / json; charset = UTF-8 '-H' Кодировка содержимого: gzip '-d' @ - '-' https://www.googleapis.com/upload/youtube/v3/videos?access_token=...&part=snippet&part=status&uploadType=resumable '<< $$$ </p>

18.06.2020 17:28:22. 900 INFO 26088 --- [main] c .google.api.client.http.HttpTransport: Всего: 144 байта

2020-06-18 17: 28: 22.902 INFO 26088 --- [main ] c .google.api.client.http.HttpTransport: {"snippet": {"categoryId": "22", "description": "Описание загруженного видео.", "Title": "Тестовая загрузка видео. "}," status ": {" privacyStatus ":" private "}}

2020-06-18 17: 28: 23.322 INFO 26088 --- [main] c .google.api.client .http.HttpTransport: -------------- ОТВЕТ --------------

HTTP / 1.1 401 Неавторизовано

Transfer-Encoding: фрагментировано

Предупреждение: 214 UploadServer gzip

Alt-Sv c: h3-28 = ": 443"; ma = 2592000, h3-27 = ": 443"; ma = 2592000, h3-25 = ": 443"; ma = 2592000, h3-T050 = ": 443"; ma = 2592000, h3-Q050 = ": 443"; ma = 2592000, h3-Q049 = ": 443"; ma = 2592000, h3-Q048 = ": 443"; ma = 2592000, h3-Q046 = ": 443"; ma = 2592000, h3-Q043 = ": 443"; ma = 2592000, quic = ": 443"; ma = 2592000; v = "46,43"

Cache-Control: private

Сервер: UploadServer

Content-Encoding: gzip

X-GUploader-UploadID: AAANsUn5M53nz45hqEKbbVNqSMaAIK9KOfY53I0TeGum-0GkPUE9YkgpeF4tDIL3x973oQwG_JXGnWljYPH9uQBQFQ

Варьируется: Источник

* * 110: 05 GMT

Content-Type: application / json; charset = UTF-8

// You need to set this value for your code to compile.
    // For example: ... DEVELOPER_KEY = "YOUR ACTUAL KEY";
    private static final String DEVELOPER_KEY = "...";
    /**
     * Build and return an authorized API client service.
     *
     * @return an authorized API client service
     * @throws GeneralSecurityException, IOException
     */
    public static YouTube getService() throws GeneralSecurityException, IOException {
        final NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        return new YouTube.Builder(httpTransport, JSON_FACTORY, null)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }
    private static final Collection<String> SCOPES =
            Arrays.asList("https://www.googleapis.com/auth/youtube.upload");

    private static final String APPLICATION_NAME = "ADAM";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();



    @Test
    public void test1()
            throws GeneralSecurityException, IOException, GoogleJsonResponseException {
        YouTube youtubeService = getService();
        Credential credential = GoogleAuthenticationUtil.getCredential("...");
        // Define the Video object, which will be uploaded as the request body.
        Video video = new Video();
        String accessToken = credential.getAccessToken();
        // Add the snippet object property to the Video object.
        VideoSnippet snippet = new VideoSnippet();
        snippet.setCategoryId("22");
        snippet.setDescription("Description of uploaded video.");
        snippet.setTitle("Test video upload.");
        video.setSnippet(snippet);

        // Add the status object property to the Video object.
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("private");
        video.setStatus(status);

        // TODO: For this request to work, you must replace "YOUR_FILE"
        //       with a pointer to the actual file you are uploading.
        //       The maximum file size for this operation is 137438953472.
        File mediaFile = new File("E:\\57086854184752465.mp4");
        InputStreamContent mediaContent =
                new InputStreamContent("application/octet-stream",
                        new BufferedInputStream(new FileInputStream(mediaFile)));
        mediaContent.setLength(mediaFile.length());

        // Define and execute the API request
        YouTube.Videos.Insert request = youtubeService.videos()
                .insert(Arrays.asList("snippet", "status"), video, mediaContent);
        Video response = request.setAccessToken(accessToken).execute();
        System.out.println(response);
    }

1 Ответ

0 голосов
/ 18 июня 2020

Я не вижу, куда вы загружаете секретный файл клиента json. Вы пытаетесь загрузить только ключ API.

  /**
   * Initializes an authorized YouTube service object.
   *
   * @return The YouTube service object.
   * @throws IOException
   * @throws GeneralSecurityException
   */
  private static YouTube initializeAnalyticsReporting() throws GeneralSecurityException, IOException {

    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

    // Load client secrets.
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(HelloYouTube.class
            .getResourceAsStream(CLIENT_SECRET_JSON_RESOURCE)));

    // Set up authorization code flow for all authorization scopes.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
        .Builder(httpTransport, JSON_FACTORY, clientSecrets,
            YouTubeScopes.all()).setDataStoreFactory(dataStoreFactory)
        .build();

    // Authorize.
    Credential credential = new AuthorizationCodeInstalledApp(flow,
        new LocalServerReceiver()).authorize("user");
    // Construct the YouTube service object.
    return new YouTube.Builder(httpTransport, JSON_FACTORY, credential)
        .setApplicationName(APPLICATION_NAME).build();
  }
...