如何在Android Studio上使用YouTube数据API v3获得订阅者人数?
我可以播放视频,但是无法获得订阅者人数,谢谢。
最佳答案
订阅者计数是Channel类的属性。
这是一个工作示例,允许您搜索 channel ,并返回所有返回结果的订户计数。
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.YouTubeRequestInitializer;
import com.google.api.services.youtube.model.*;
import java.io.IOException;
import java.util.*;
class Main {
public static final String API_KEY = "YOUR KEY HERE";
public static void main(String[] args) throws Exception {
YouTube youtube = new YouTube.Builder(
new NetHttpTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
})
.setApplicationName("youtube-cmdline-search-sample")
.setYouTubeRequestInitializer(new YouTubeRequestInitializer(API_KEY))
.build();
Scanner input = new Scanner(System.in);
System.out.println("Search for channel:");
String queryTerm = input.nextLine();
YouTube.Search.List search = youtube.search().list("snippet");
search.setQ(queryTerm);
search.setType("channel");
SearchListResponse searchResponse = search.execute();
List<SearchResult> searchResultList = searchResponse.getItems();
if (searchResultList != null) {
for (SearchResult searchResult : searchResultList) {
String channelId = searchResult.getSnippet().getChannelId();
YouTube.Channels.List channels = youtube.channels().list("snippet, statistics");
channels.setId(channelId);
ChannelListResponse channelResponse = channels.execute();
for (Channel c : channelResponse.getItems()) {
System.out.println("Name: " + c.getSnippet().getTitle());
System.out.println("Subs: " + c.getStatistics().getSubscriberCount());
System.out.println();
}
}
}
}
}
使用输入:H3 Podcast,您将得到以下结果:
Name: H3 Podcast
Subs: 511821
Name: h3h3Productions
Subs: 4241196
Name: The H3 Podcast
Subs: 2
Name: Baited!
Subs: 236641
Name: Ethan and Hila
Subs: 1633842
我不确定是否有更好的方法可以执行此操作,但是它确实有效。