youtube api搜索响应(java)
使用java的YoutubeApi,我进行了视频搜索。 通过使用以下示例,它运行良好 ttps://developers.google.com/youtube/v3/code_samples/java#search_by_keyword 获得了以下数据youtube api搜索响应(java),java,api,youtube,Java,Api,Youtube,使用java的YoutubeApi,我进行了视频搜索。 通过使用以下示例,它运行良好 ttps://developers.google.com/youtube/v3/code_samples/java#search_by_keyword 获得了以下数据 { "Items": [ search resource ] } 我想要“NextPageToken”和“PrevPageToken”。 因此,我添加了以下代码 searchResponse.getNextPag
{
"Items": [
search resource
]
}
我想要“NextPageToken”和“PrevPageToken”。
因此,我添加了以下代码
searchResponse.getNextPageToken()
但结果是“空”
我怎么了
参考:ttps://developers.google.com/youtube/v3/docs/search/list
这是密码,谢谢
/* *版权所有(c)2012谷歌公司。 * *根据Apache许可证2.0版(以下简称“许可证”)获得许可;您不能使用此文件,除非 *符合许可证的要求。您可以通过以下方式获得许可证副本: * * * *除非适用法律要求或书面同意,否则根据许可证分发的软件 *在“按原样”的基础上分发,无任何形式的保证或条件,无论是明示的还是明示的 *或者暗示。请参阅下面的许可证,了解管理权限和限制的特定语言 *执照。 */
package com.google.api.services.samples.youtube.cmdline.youtube\u cmdline\u search\u sample;
导入com.google.api.client.googleapis.json.GoogleJsonResponseException;
导入com.google.api.client.http.HttpRequest;
导入com.google.api.client.http.HttpRequestInitializer;
导入com.google.api.client.http.HttpTransport;
导入com.google.api.client.http.javanet.NetHttpTransport;
导入com.google.api.client.json.JsonFactory;
导入com.google.api.client.json.jackson2.JacksonFactory;
导入com.google.api.services.youtube.youtube;
导入com.google.api.services.youtube.youtube.Search;
导入com.google.api.services.youtube.model.ResourceId;
导入com.google.api.services.youtube.model.SearchListResponse;
导入com.google.api.services.youtube.model.SearchResult;
导入com.google.api.services.youtube.model.缩略图;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.Iterator;
导入java.util.List;
导入java.util.Properties;
/**
*根据搜索词打印视频列表。
*
*@作者杰里米·沃克
*/
公共类Youtube_示例_2{
/**全局实例属性文件名*/
私有静态字符串属性\u FILENAME=“youtube.PROPERTIES”;
/**HTTP传输的全局实例*/
私有静态最终HttpTransport HTTP_TRANSPORT=new NetHttpTransport();
/**JSON工厂的全局实例*/
私有静态最终JsonFactory JSON_FACTORY=new JacksonFactory();
/**我们希望返回的最大视频数的全局实例(50=每页的上限)*/
返回的私有静态最终长视频数=25;
/**用于发出所有API请求的Youtube对象的全局实例*/
私有静态YouTube YouTube;
/**
*初始化YouTube对象以搜索YouTube上的视频(YouTube.search.List)
*然后打印每个视频的名称和缩略图(仅前50个视频)。
*
*@param args命令行args。
*/
公共静态void main(字符串[]args){
//从youtube.properties读取开发者密钥
属性=新属性();
试一试{
InputStream in=Search.class.getResourceAsStream(“/”+属性\u文件名);
属性。荷载(in);
}捕获(IOE异常){
System.err.println(“读取“+PROPERTIES\u FILENAME+”:“+e.getCause()时出错)
+“:”+e.getMessage());
系统出口(1);
}
试一试{
/*
*YouTube对象用于发出所有API请求。最后一个参数是必需的,但
*因为在初始化HttpRequest时不需要初始化任何内容,所以我们重写
*接口并提供无操作功能。
*/
youtube=new youtube.Builder(HTTP_传输、JSON_工厂、新的HttpRequestInitializer(){
公共无效初始化(HttpRequest请求)引发IOException{}
}).setApplicationName(“youtube cmdline搜索示例”).build();
//从用户处获取查询条件。
字符串queryTerm=getInputQuery();
YouTube.Search.List Search=YouTube.Search().List(“id,snippet”);
//System.out.println(搜索);
/*
*从Google开发者控制台设置开发者密钥非常重要
*未经身份验证的请求(可在此链接的API访问选项卡下找到:
*code.google.com/api/)。这是一个很好的做法,增加了您的配额。
*/
字符串apiKey=properties.getProperty(“youtube.apiKey”);
search.setKey(apiKey);
search.setQ(queryTerm);
/*
*我们只搜索视频(不是播放列表或频道)。如果我们搜索
*此外,我们会将它们添加为如下字符串:“视频、播放列表、频道”。
*/
search.setType(“视频”);
/*
*此方法减少了仅返回到我们需要的字段的信息,并进行了更多调用
*效率高。
*/
search.setFields(“项(id/kind、id/videoId、片段/标题、片段/缩略图/默认值/url)”;
search.setMaxResults(返回的视频数量);
SearchListResponse searchResponse=search.execute();
System.out.println(searchResponse);
//System.out.println(searchResponse.getNextPageToken());
//System.out.println(searchResponse.getPageInfo());
List searchResultList=searchResponse.getItems();
//System.out.println(searchResultList);
if(searchResultList!=null){
预打印(searchResultList.iterator(),queryTerm);
}
}捕获(GoogleJsonResponseException e){
System.err.println(“出现服务错误:+e.getDetails().getCode()+”:“
+e.getDetails().getMessage());
}捕获(IOE异常){
System.err.println(“有一个IO错误:“+e.getCause()+”:“+e.getMessage());
}捕获(可丢弃的t){
t、 printStackTrace();
}
}
package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_search_sample;
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.HttpTransport;
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.YouTube.Search;
import com.google.api.services.youtube.model.ResourceId;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import com.google.api.services.youtube.model.Thumbnail;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
/**
* Prints a list of videos based on a search term.
*
* @author Jeremy Walker
*/
public class Youtube_sample_2 {
/** Global instance properties filename. */
private static String PROPERTIES_FILENAME = "youtube.properties";
/** Global instance of the HTTP transport. */
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
/** Global instance of the max number of videos we want returned (50 = upper limit per page). */
private static final long NUMBER_OF_VIDEOS_RETURNED = 25;
/** Global instance of Youtube object to make all API requests. */
private static YouTube youtube;
/**
* Initializes YouTube object to search for videos on YouTube (Youtube.Search.List). The program
* then prints the names and thumbnails of each of the videos (only first 50 videos).
*
* @param args command line args.
*/
public static void main(String[] args) {
// Read the developer key from youtube.properties
Properties properties = new Properties();
try {
InputStream in = Search.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
properties.load(in);
} catch (IOException e) {
System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause()
+ " : " + e.getMessage());
System.exit(1);
}
try {
/*
* The YouTube object is used to make all API requests. The last argument is required, but
* because we don't need anything initialized when the HttpRequest is initialized, we override
* the interface and provide a no-op function.
*/
youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {}
}).setApplicationName("youtube-cmdline-search-sample").build();
// Get query term from user.
String queryTerm = getInputQuery();
YouTube.Search.List search = youtube.search().list("id,snippet");
// System.out.println(search);
/*
* It is important to set your developer key from the Google Developer Console for
* non-authenticated requests (found under the API Access tab at this link:
* code.google.com/apis/). This is good practice and increased your quota.
*/
String apiKey = properties.getProperty("youtube.apikey");
search.setKey(apiKey);
search.setQ(queryTerm);
/*
* We are only searching for videos (not playlists or channels). If we were searching for
* more, we would add them as a string like this: "video,playlist,channel".
*/
search.setType("video");
/*
* This method reduces the info returned to only the fields we need and makes calls more
* efficient.
*/
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
SearchListResponse searchResponse = search.execute();
System.out.println(searchResponse);
// System.out.println(searchResponse.getNextPageToken());
// System.out.println(searchResponse.getPageInfo());
List<SearchResult> searchResultList = searchResponse.getItems();
// System.out.println(searchResultList);
if (searchResultList != null) {
prettyPrint(searchResultList.iterator(), queryTerm);
}
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (IOException e) {
System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
}
/*
* Returns a query term (String) from user via the terminal.
*/
private static String getInputQuery() throws IOException {
String inputQuery = "";
System.out.print("Please enter a search term: ");
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
inputQuery = bReader.readLine();
if (inputQuery.length() < 1) {
// If nothing is entered, defaults to "YouTube Developers Live."
inputQuery = "YouTube Developers Live";
}
return inputQuery;
}
/*
* Prints out all SearchResults in the Iterator. Each printed line includes title, id, and
* thumbnail.
*
* @param iteratorSearchResults Iterator of SearchResults to print
*
* @param query Search query (String)
*/
private static void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query) {
System.out.println("\n=============================================================");
System.out.println(
" First " + NUMBER_OF_VIDEOS_RETURNED + " videos for search on \"" + query + "\".");
System.out.println("=============================================================\n");
if (!iteratorSearchResults.hasNext()) {
System.out.println(" There aren't any results for your query.");
}
while (iteratorSearchResults.hasNext()) {
SearchResult singleVideo = iteratorSearchResults.next();
ResourceId rId = singleVideo.getId();
// Double checks the kind is video.
if (rId.getKind().equals("youtube#video")) {
Thumbnail thumbnail = (Thumbnail) singleVideo.getSnippet().getThumbnails().get("default");
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");
}
}
}
}
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url),nextPageToken,pageInfo,prevPageToken");
SearchListResponse searchResponse = search.execute();
String nextPageToken = searchResponse.getNextPageToken();