目標: 實現一個程序(java或python)從我在Youtube頻道上發佈的視頻中檢索數據。 此計劃將每天(凌晨1:00)啓動。Youtube Analytics和Google服務帳戶
解決方案: 要檢索數據Youtube,包括每天的觀看次數,YouTube Analytics API在我看來是最好的解決方案。我使用谷歌帳戶服務( 「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();
}
}
我執行YouTube分析查詢:
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();
}
,但我得到了以下錯誤:
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."
}
感謝您的洞察!