youtube service api返回的渠道ID无效

时间:2014-03-04 13:11:45

标签: java api youtube oauth-2.0 youtube-analytics

我正在尝试使用com.google.api.services.youtube.YouTube类从Java应用中获取我的YouTube频道列表。 。

首先,我启用了服务帐户凭据(https://console.developers.google.com>凭据),并启用了以下API: -YouTube Analytics API -YouTube Data API -Analytics API

要调用Youtube服务,我使用以下代码创建一个Credential对象。


/** Global instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

private static Credential authorize() throws Exception 
{

List<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/youtube");  
    scopes.add("https://www.googleapis.com/auth/yt-analytics.readonly");
    scopes.add("https://www.googleapis.com/auth/youtube.readonly");
    scopes.add("https://www.googleapis.com/auth/youtubepartner-channel-audit");

    GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
        .setJsonFactory(JSON_FACTORY)
        .setServiceAccountPrivateKeyFromP12File(new File("C://file.privatekey.p12"))
        .setServiceAccountId("xxxx-yyyyyyyyyyyyyy@developer.gserviceaccount.com")
        .setServiceAccountScopes(scopes)
        .build();
        return credential;
  }

之后我打电话给Youtube服务来获取我的频道


/** Global instance of the HTTP transport. */
  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();


  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = new JacksonFactory();


  /** Global instance of Youtube object to make general YouTube API requests. */
  private static YouTube youtube;

  /** Global instance of YoutubeAnalytics object to make analytic API requests. */
  private static YouTubeAnalytics analytics;


public String getDefaultChannelId(){
      try{
      Credential credential = authorize();
      // YouTube object used to make all non-analytic API requests.
      youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
        .setApplicationName("API Project")
        .build();

      YouTube.Channels.List channelRequest = youtube.channels().list("id,snippet");
      channelRequest.setMine(true);
      channelRequest.setMaxResults(50L);
    channelRequest.setFields("items(id,snippet/title,contentDetails,status,kind,etag,auditDetails)");
      ChannelListResponse channels = channelRequest.execute();

      System.out.println(channels.getItems());

      // List of channels associated with user.
      List<Channel> listOfChannels = channels.getItems();

      // Grab default channel which is always the first item in the list.
      Channel defaultChannel = listOfChannels.get(0);
      String channelId = defaultChannel.getId();
      return channelId;
    }catch(Exception ex){
      ex.printStacktrace();
    }
}

授权代码似乎没有任何问题。问题在于getDefaultChannelId()方法,它返回一个id为UC9i22sTxrX0IQk4AkT_Og3w的通道。 我尝试使用浏览器导航到我的youtube频道,使用网址:http://www.youtube.com/channel/UC9i22sTxrX0IQk4AkT_Og3w但该频道不存在..

我用来打印通道的行结果是“System.out.println(channels.getItems());”显示以下json字符串。

[{"etag":"\"BDC7VThyM9nfoSQm1_kOyhtJTEw/yJvLzly7DMctrvFV5drOtgksadM\"","id":"UC9i22sTxrX0IQk4AkT_Og3w","kind":"youtube#channel","snippet":{"title":""}}

由于某种原因,youtube服务不会返回特定凭据对象的正确通道列表。 但为什么????

1 个答案:

答案 0 :(得分:2)

您无法在Youtube API中使用服务帐户:https://developers.google.com/youtube/v3/guides/moving_to_oauth#service_accounts。 Youtube API应该会引发服务帐户的错误,但显然它不会。

您应该创建一个类型为Installed Application的客户端ID,然后为您的用户检索刷新令牌(https://developers.google.com/accounts/docs/OAuth2InstalledApp)并使用此令牌创建凭据。

这是一个示例(存储clientId,clientSecret,refreshToken和accessToken,只要你保密,就应该缓存令牌响应):

private String clientId;
private String clientSecret;
private String refreshToken;
private String accessToken;
private TokenResponse tokenResponse;

private Credential createCredential() {
    final GoogleCredential.Builder builder = new GoogleCredential.Builder();
    builder.setTransport(HTTP_TRANSPORT);
    builder.setJsonFactory(JSON_FACTORY);
    builder.setClientSecrets(clientId, clientSecret);
    builder.addRefreshListener(new CredentialRefreshListener() {
        @Override
        public void onTokenResponse(final Credential credential,
                final TokenResponse tokenResponse) throws IOException {
            this.tokenResponse = tokenResponse;
        }

        @Override
        public void onTokenErrorResponse(final Credential credential,
                final TokenErrorResponse tokenErrorResponse)
                throws IOException {
            this.tokenResponse = null;
            // trace error
        }
    });
    return builder.build();
}

private YouTube getYoutube() {
    final Credential credential = createCredential();
    if (this.tokenResponse == null) {
        credential.setAccessToken(this.accessToken);
        credential.setRefreshToken(this.refreshToken);
    } else {
        credential.setFromTokenResponse(this.tokenResponse);
    }

    final YouTube youtube = new YouTube.Builder(HTTP_TRANSPORT,
            JSON_FACTORY, credential).setApplicationName("*****").build();
    return youtube;
}