use*_*335 2 java youtube youtube-api oauth-2.0 service-accounts
目标: 实现一个程序(java或python)以从我在YouTube频道上发布的视频中检索数据。该程序将每天(1:00 AM)启动。
解决方案: 要检索YouTube数据,包括每天的观看次数,我认为YouTube Analytics API是最好的解决方案。我使用Google帐户服务(“ GoogleCredential”)对我进行身份验证:
static {
// Build service account credential.
try {
// Create a listener for automatic refresh OAuthAccessToken
List<CredentialRefreshListener> list = new ArrayList<CredentialRefreshListener>();
list.add(new CredentialRefreshListener() {
public void onTokenResponse(Credential credential,
TokenResponse tokenResponse) throws IOException {
System.out.println(tokenResponse.toPrettyString());
}
public void onTokenErrorResponse(Credential credential,
TokenErrorResponse tokenErrorResponse)
throws IOException {
System.err.println("Error: "
+ tokenErrorResponse.toPrettyString());
}
});
// Create a GoogleCredential for authenticate with ServiceAccount
// service
credential = new GoogleCredential.Builder()
.setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(SCOPES)
.setClock(Clock.SYSTEM)
.setServiceAccountPrivateKeyFromP12File(
new File("key.p12"))
.setRefreshListeners(list).build();
credential.refreshToken();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
然后执行Youtube Analytics查询:
YoutubeAnalytics youtubeAnalytics = new YoutubeAnalytics.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName("Test-YouTube-Analytics/1.0").build();
// Create request
credential.refreshToken();
YoutubeAnalyticsRequest<?> request = youtubeAnalytics.reports()
.query("channel==" + channelId, "2012-10-01", "2012-12-01", "views")
.setAlt("json")
.setKey(API_KEY)
.setDimensions("month")
.setPrettyPrint(true);
System.out.println(request.buildHttpRequest().getUrl().toString());
ResultTable first = (ResultTable) request.execute();
}
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 500 Internal Server Error
{
"code" : 500,
"errors" : [ {
"domain" : "global",
"message" : "Unknown error occurred on the server.",
"reason" : "internalError"
} ],
"message" : "Unknown error occurred on the server."
}
Run Code Online (Sandbox Code Playgroud)
感谢您的见解!
发出YouTube Analytics API请求时,您不能使用服务帐户。您需要使用的帐户既可以是YouTube频道的所有者,也可以使用与该频道相关联的内容的所有者,但我认为服务帐户不能是上述任何一种。请以拥有YouTube频道的Google帐户登录的方式访问OAuth 2流程一次,以后保存的OAuth 2刷新令牌可能会在以后重复使用,以获取可用于运行报告的最新访问令牌。
您能否解决该问题,然后尝试再次运行报告?
| 归档时间: |
|
| 查看次数: |
2153 次 |
| 最近记录: |