java - 如何通过身份验证的Google服务帐户调用youtube API以在Java中生成 token

标签 java youtube

我正在开发用于获取特定youtube视频详细信息的Web应用程序。为此,我使用了Google服务帐户进行了诸如 call 授权过程之类的代码。我认为身份验证已完成且未生成 token 。在我运行我的代码时,它收到了类似“INVALID_GRANT”的错误“。请帮助我解决此问题。

        here my sample code is as:

    String clientId = "Something.apps.googleusercontent.com";
                @SuppressWarnings({ "unchecked", "rawtypes" })
                List<String>scops = new <String>ArrayList();
                scops.add("https://www.googleapis.com/auth/youtubepartner");
                final HttpTransport TRANSPORT = new NetHttpTransport();
                final JsonFactory JSON_FACTORY = new JacksonFactory();

                GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(TRANSPORT)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(clientId)
                .setServiceAccountScopes(scops)
                .setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
                .build();
                System.out.println("credential............."+credential);
                YouTube youtube=new YouTube.Builder(TRANSPORT, JSON_FACTORY, credential).setApplicationName("test").build();
                System.out.println("Responce.............."+youtube);
                com.google.api.services.youtube.YouTube.Activities act=youtube.activities();
                com.google.api.services.youtube.YouTube.Activities.List list=act.list("");
                list.execute();
                System.out.println("list Details...................."+list);

    here i passes Youtube Api to retrieving the list.

    error :

    Exceptioncom.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
    {
      "error" : "invalid_grant"
    }

    i m waiting for all of ur response to resolve this problem..Thanks all once again to spend time with my pro

最佳答案

我对您的身份验证方法不是很熟悉,但是有两件事:

.setServiceAccountId(clientId)中的

  • 中,您使用 clientId 作为参数,但是在纪录片中,它通常是电子邮件地址:

  • Builder com.google.api.client.googleapis.auth.oauth2.GoogleCredential.Builder.setServiceAccountId(String serviceAccountId)

    @Beta

    Beta

    Sets the service account ID (typically an e-mail address) or null for none.



    .setServiceAccountPrivateKeyFromP12File(new File("key.p12"))中的
  • 中,您指定了一个名为 key.p12的文件,它不是
  • 文件

    抱歉,如果您的代码不是真正的代码,仅用于演示目的。

    如果这两件事都无济于事,您可以尝试以下方法(对我有用):
            // FileDataStoreFactory is used to create new credentials and 
            // simultaneously loads previously generated credentials from a file
            // Specify a location where the file should be stored via DIRECTORY
            // The file is automatically generated and encrypted
            FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(DIRECTORY));
    
            // Create the GoogleAuthorizationCodeFlow. This is needed to get the user (you?)
            // approval (you need that so you can access data). getClientSecrets() returns a
            // GoogleClientSecrets. If you want to, I can provide some code :)
            // Here you also specify your scopes
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, getClientSecrets(), Arrays.asList(scope))
                .setCredentialDataStore(StoredCredential.getDefaultDataStore(fileDataStoreFactory)).build();
    
            // With the GoogleAuthorizationCodeFlow you can create a Credential
            Credential cred = flow.loadCredential("user");
    
            // Check if the cred is null or expired (credentials last about an hour I think)
            if(cred == null || (cred.getExpiresInSeconds() < 100 && !cred.refreshToken())){
                // If it is expired, you need to refresh it via UserAuthorization, again, if you
                // want to I can provide an example code
                GoogleTokenResponse resp = getUserAuthorization(flow);
                if(resp == null){
                    return null;
                }
                cred = flow.createAndStoreCredential(resp, "user");
            }
    
    您可以在代码中完全像GoogleCredential一样使用Credential:
                System.out.println("credential............."+ cred);
                YouTube youtube=new YouTube.Builder(TRANSPORT, JSON_FACTORY, cred).setApplicationName("test").build();
                System.out.println("Responce.............."+youtube);
                com.google.api.services.youtube.YouTube.Activities act=youtube.activities();
                com.google.api.services.youtube.YouTube.Activities.List list=act.list("");
                list.execute();
                System.out.println("list Details...................."+list);
    
    我希望这有帮助 :)

    为此,我遵循了本教程:Google's Tutorial
    对于服务器端应用程序:Google's Tutorial about server-side applications
    以及使用JavaScript的网络应用程序:Google's Tutorial about web-applications

    关于java - 如何通过身份验证的Google服务帐户调用youtube API以在Java中生成 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27529582/

    相关文章:

    javascript - Youtube API v3 按位置搜索视频

    java - 我可以从 System.nanoTime 合理预期的最差分辨率是多少?

    java - HTTP 状态 500 - java.lang.NoClassDefFoundError : java/time/temporal/TemporalField when run app on OpenShift

    java - 使用 UUID 作为 Hibernate 主键 id 是否被认为是糟糕的设计?

    java - Eclipse XML 格式化后端库

    python - 如何使用 python 在我的 youtube 历史记录中获取最后观看的视频?

    javascript - 显示 :none not working on iPhone simulator

    java - Groovy CompileStatic 中的奇怪字节码

    python - 使用 python-vlc 和 pafy 的 python 脚本出错

    java - 使用 API 的 Youtube 视频的最大评论数?