Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

How to access YouTube view count with Java API

I found this answer that shows how to get a video's view count with the Java YouTube API but clearly some things must have changed over the last 7 years or so because I can't figure out the code.

This line

YouTube.Videos.List list = youtube.videos().list("statistics");

produces an error in Eclipse because the list method from the class Videos(at least in the current API version) has a parameter of type List<String>not String...so can someone show me how to achieve my goal using the current API seeing as the code linked above is invalid due to changes to the API?

EDIT: Here is how I have defined my dependency for the YouTube API in my pom.xml file

<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-youtube</artifactId>
  <version>v3-rev20201202-1.31.0</version>
</dependency>
question from:https://stackoverflow.com/questions/65602234/how-to-access-youtube-view-count-with-java-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thanks to a little help from stvar and of course the old question I linked to in my question I figured out what I needed to do. Here is the working code:

import java.io.IOException;
import java.util.Arrays;

import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.youtube.*;
import com.google.api.services.youtube.model.Video;

public class Main {
    public static void main(String[] args) throws IOException
    {
        YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-view-count-test").build();
    
        YouTube.Videos.List list = youtube.videos().list(Arrays.asList("statistics"));
        list.setId(Arrays.asList("kffacxfA7G4"));
        String apiKey = "[redacted]";
        list.setKey(apiKey);            
        Video v = list.execute().getItems().get(0);
        System.out.println("The view count is: "+v.getStatistics().getViewCount());
    }
}

The Auth class that is used in my code is taken from here, part of Google's API samples


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...