我正在编写一个使用YouTube Data v3的Java应用程序。我想要能够确定一个频道的上传率。例如,如果一个频道有一个星期的历史,并且已经发布了两个视频,我想要一些方法来确定这个频道的上传率是每周2个视频。我将如何使用YouTube API来完成这个任务?
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
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.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Collection;
import java.util.Collections;
import java.util.Properties;
public class ApiExample {
public static void main(String[] args)
throws GeneralSecurityException, IOException, GoogleJsonResponseException {
Properties properties = new Properties();
try {
InputStream in = ApiExample.class.getResourceAsStream("/" + "youtube.properties");
properties.load(in);
} catch (IOException e) {
System.err.println("There was an error reading " + "youtube.properties" + ": " + e.getCause()
+ " : " + e.getMessage());
System.exit(1);
}
YouTube youtubeService = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("API Demo").build();
// Define and execute the API request
YouTube.Channels.List request = youtubeService.channels()
.list("snippet,contentDetails,statistics");
String apiKey = properties.getProperty("youtube.apikey");
request.setKey(apiKey);
ChannelListResponse response = request.setId("UC_x5XG1OV2P6uZZ5FSM9Ttw").execute();
for (Channel channel : response.getItems()) {
/* What do I do here to get the individual channel's upload rate? /
}
}
}
上面的示例使用了YouTube开发人员通道,但是我希望能够在任何通道上做到这一点。
发布于 2020-09-29 16:32:55
根据官方文档,一旦调用了Channels.list
API端点--该端点返回指定通道的元数据( Channels resource
) --您就可以使用以下属性:
(未签名的long)
上传到频道的公开视频数量。
因此,事情几乎是显而易见的:使此属性返回的值持久(例如,将其保存到一个文件中),并安排您的程序,以便每周发布一次,以计算所需的上传速率。
现在,对于上面提到的代码,您首先应该去掉:
for (Channel channel : response.getItems()) {
/* What do I do here to get the individual channel's upload rate? /
}
因为items
属性最多包含一个项。一个好的做法是坚持这一条件:
assert response.getItems().size() <= 1;
所需的videoCount
属性的值可以在ChannelStatistics
类的方法getVideoCount
下访问:
response.getItems().get(0).getStatistics().getVideoCount()
。
当然,由于向API询问真正有用的信息总是很好的,所以我还建议您使用参数fields
(方法setFields
)的形式:
request.setFields("items(statistics(videoCount))")
,
例如,插入在request.setKey(apiKey)
之后。
这样,API将只向您发送您需要的属性。
增编
我还必须指出,上面的断言只有在传递给API端点时才是正确的(就像您目前在代码中所做的那样)只有一个通道ID。如果将来您想一次计算N
通道的上传速率(使用N <= 50
),那么上面的条件将类似于size() <= N
。
在多个通道上一次调用Channels.list
是可能的,因为该端点的id
属性允许指定为一个以逗号分隔的通道ID列表。
https://stackoverflow.com/questions/64123167
复制相似问题