我们使用 google-api-java-client 来查找视频,我们想知道是否可以获取在特定日期(从昨天到现在)发布的特定标签(比如体育)上的视频。我该怎么做呢?
user899876
问问题
627 次
1 回答
2
我能够使用 google-api-client 1.6.0-beta (通过Maven下载)来做到这一点。我稍微修改了示例代码。自从编写示例代码以来,API 发生了细微的变化。我添加了YouTube API 参考指南中的查询参数,并扩展了 Video 类以包含更多字段。如果您查看从查询返回的原始 JSON,您会看到您可以添加其他几个字段,包括缩略图、持续时间、纵横比、评论计数等。我希望这会有所帮助。
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.json.JsonCParser;
import com.google.api.client.http.*;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.util.List;
public class YouTubeSample {
public static class VideoFeed {
@Key
List<Video> items;
}
public static class Video {
@Key
String title;
@Key
String description;
@Key
Player player;
@Key
String uploaded;
@Key
String category;
@Key
String[] tags;
}
public static class Player {
@Key("default")
String defaultUrl;
}
public static class YouTubeUrl extends GenericUrl {
@Key
final String alt = "jsonc";
@Key
String author;
@Key("max-results")
Integer maxResults;
@Key
String category;
@Key
String time;
YouTubeUrl(String url) {
super(url);
}
}
public static void main(String[] args) throws IOException {
// set up the HTTP request factory
HttpTransport transport = new NetHttpTransport();
final JsonFactory jsonFactory = new JacksonFactory();
HttpRequestFactory factory = transport.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) {
// set the parser
JsonCParser parser = new JsonCParser(jsonFactory);
request.addParser(parser);
// set up the Google headers
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("Google-YouTubeSample/1.0");
headers.gdataVersion = "2";
request.setHeaders(headers);
}
});
// build the YouTube URL
YouTubeUrl url = new YouTubeUrl("https://gdata.youtube.com/feeds/api/videos");
url.maxResults = 10;
url.category = "sports";
// Time options: today, this_week, this_month, all_time
url.time = "today";
// build the HTTP GET request
HttpRequest request = factory.buildGetRequest(url);
// execute the request and the parse video feed
VideoFeed feed = request.execute().parseAs(VideoFeed.class);
// Useful for viewing raw JSON results
//System.out.println(request.execute().parseAsString());
for (Video video : feed.items) {
System.out.println();
System.out.println("Video title: " + video.title);
System.out.println("Description: " + video.description);
System.out.println("Play URL: " + video.player.defaultUrl);
System.out.println("Uploaded: " + video.uploaded);
System.out.println("Category: " + video.category);
System.out.print("Tags: ");
for(String tag: video.tags){
System.out.print(tag + " ");
}
System.out.println();
}
}
}
于 2012-02-17T21:14:34.607 回答