当前位置: 首页 > 知识库问答 >
问题:

youtube-api搜索响应(java)

须巴英
2023-03-14

使用爪哇的优酷Api,我做了一个视频搜索。通过使用以下示例,它运行良好。

ttps://developers.google.com/youtube/v3/code_samples/java#search_by_keyword

获得了以下数据

{
    "Items": [
        search resource
    ]
}

我想要“NextPageToken”和“PrevPageTokens”。所以我添加了以下代码。

searchResponse.getNextPageToken();

但结果是“空”;

我错了什么?

参考:ttps://developers.google.com/youtube/v3/docs/search/list

这是密码,谢谢

/**版权所有(c)2012 Google Inc.**根据Apache许可证2.0版(“许可证”)获得许可;除非*符合许可证,否则您不得使用此文件。您可以在**http://www.apache.org/licenses/LICENSE-2.0**获得许可证的副本,除非适用法律要求或书面同意,否则根据许可证*分发的软件是按“原样”分发的,没有任何明示*或暗示的保证或条件。有关*许可证下管理权限和限制的特定语言,请参阅许可证。*/

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");
      }
    }
  }
}

这是螺旋桨文件。

youtube属性

youtube.apikey=AIzaSyDLnvt0SJRc4hLUWQBiLxkGFLWbsjsRvjQ

共有2个答案

丘学海
2023-03-14

用户65415642,

我不知道java的youtube api,但我已经在我的应用程序中完成了youtube api,即iphone应用程序(ios)。

搜索字符串=[NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/search?part=snippet

通过调用这个url,您可以使用nextpage令牌获得响应

谯英彦
2023-03-14

您必须更改setFields方法参数,如下所示:

search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url),nextPageToken,pageInfo,prevPageToken");

然后调用execute方法:

SearchListResponse searchResponse = search.execute();

现在您将获得下一页令牌:

String nextPageToken = searchResponse.getNextPageToken();

如果你想从YouTube获得50多个视频,那么我在GitHub上创建了一个拉取请求,请查看完整的Search.java文件。

 类似资料:
  • 我正在调用YouTube API,截至上周,它不再始终如一地在特定频道上查找最新发布的视频。 我正在使用文档中实际的“尝试这个API”窗口(这里有一个已经输入参数的链接): https://developers.google.com/youtube/v3/docs/search/list?apix_params={"part":"snippet "," channelId ":" uci8e 0

  • 我只是想在youtube上搜索我自己的视频,在X日期后发布 然而,当我使用< code>publishAfter参数时,即使我将< code>type参数设置为< code>video,也会出现< code>invalidSearchFilter错误。 错误描述如下: 该请求包含无效的搜索过滤器和/或限制组合。请注意,如果您将或参数设置为,则必须将参数设置为,如果您为、、、、、、、、或参数设置值,

  • 假设我们有以下 API: 没有客人匹配条件时,我应该返回哪个状态码?我的意思是没有名字为假人的客人。 它应该是带有空数组的、还是

  • 这样地:http://gdata.youtube.com/feeds/api/videos?alt=rss 我可以同时搜索作者和关键词, 但是我在v3版本中找不到它 https://www.googleapis.com/youtube/v3/search?part=snippet

  • 问题内容: 我试图以编程方式在Microsoft Bing搜索引擎上执行搜索。 这是我的理解: 有一个Bing Search API 2.0,即将被替换(2012年8月1日) 新的API被称为Windows Azure Marketplace。 两者使用不同的URL。 在旧的API(Bing Search API 2.0)中 ,您在URL中指定一个密钥(应用程序ID),该密钥将用于验证请求。只要您

  • 从今天开始: "http://gdata.youtube.com/feeds/api/videos?q=nexus 不给我任何结果,其中“http://gdata.youtube.com/feeds/api/videos?q=nexus 我注意到它可以在我的家用笔记本电脑上运行,但不能在我的生产服务器上运行。有没有可能youtube把我的服务器IP列入黑名单?但是我得到了没有LR参数的结果....