Get View Count in YouTube V3 API for java

2019-02-15 14:47发布

问题:

How can I get the information of how many views a certain video of YouTube has by providing the videoID of it using Java API?

for example in the code sample that their provide they print different properties. How can I add printing the view Count?

Java code:

        SearchResult singleVideo = iteratorSearchResults.next();
        ResourceId rId = singleVideo.getId();

        // Confirm that the result represents a video. Otherwise, the
        // item will not contain a video ID.
        if (rId.getKind().equals("youtube#video")) {
            Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault();

            System.out.println(" Video Id" + rId.getVideoId());
            System.out.println(" Title: " + singleVideo.getSnippet().getTitle());
            System.out.println(" Thumbnail: " + thumbnail.getUrl());
            System.out.println("\n-------------------------------------------------------------\n");

here is a very similar question to mine, also unanswered:
Get ViewCount in Search.List - Youtube Data API v3

update 30/9: According to Youtube API tutorial the video resource may contain the following parts:

  • snippet
  • contentDetails
  • fileDetails
  • player
  • processingDetails
  • recordingDetails
  • statistics
  • status
  • suggestions
  • topicDetails

but in the SearchResult object only expose getSnippet() out of all of them

I also couldn't use a different part except the 'snippet' in the API Explorer that google provides.

So maybe all these statistics properties are not supported yet by API V3??

回答1:

After getting the "id" here, you should do a videos->list call, to get video properties like "viewcount".

Here's sample: https://github.com/youtube/api-samples/blob/master/java/src/main/java/com/google/api/services/samples/youtube/cmdline/data/GeolocationSearch.java#L142



回答2:

OK I got it the code to do it is:

YouTube.Videos.List list = youtube.videos().list("statistics");
list.setId("kffacxfA7G4");
list.setKey("your private API KEY");            
Video v = list.execute().getItems().get(0);
        System.out.println("The view count is: "+v.getStatistics().getViewCount());

This video BTW exceed the billion views - Justim Bieber rules! (-;



回答3:

Once you get a video id, you could make a Video-List get call with the below query parameters.

GET https://www.googleapis.com/youtube/v3/videos?part=statistics&id={Video_ID}&key={YOUR_API_KEY}

You could try Youtube api v3 tool to check https://developers.google.com/youtube/v3/docs/videos/list