How to retrieve details of single video from youtube using videoID through Data API v3.0 in Android?

前提是你 提交于 2019-12-19 09:06:04

问题


My server sends the list of videoID to Android. Now, I want to show Title, Thumbnail and Number of Comments on these videos in List View. I have done this in web using GET request to https://www.googleapis.com/youtube/v3/videos?part=snippet&id={VIDEO_ID}&key={YOUR_API_KEY} but how to do this in Android? Is there any YouTube SDK to initialize YouTube object? How do I retrieve this information from YouTube using VideoID?

EDIT: I have found a way to this using YouTube Data API Client Library for Java but It is giving runtime error without any explanation.

Here is the code I used

/**
 * Define a global instance of a Youtube object, which will be used
 * to make YouTube Data API requests.
 */
private static YouTube youtube;

youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer(){
        public void initialize(com.google.api.client.http.HttpRequest request) throws IOException {
        }
    }).setApplicationName("youtube-cmdline-search-sample").build();

// Call the YouTube Data API's videos.list method to retrieve videos.
    VideoListResponse videoListResponse = youtube.videos().
        list("snippet").setId(videoId).execute();

    // Since the API request specified a unique video ID, the API
    // response should return exactly one video. If the response does
    // not contain a video, then the specified video ID was not found.
    List<Video> videoList = videoListResponse.getItems();
    if (videoList.isEmpty()) {
        System.out.println("Can't find a video with ID: " + videoId);
        return;
    }
    Video video = videoList.get(0)
    // Print information from the API response.
}

回答1:


YouTube provides (at least) two official libraries relevant to your question:

  • YouTube Android Player API
  • YouTube Data API Client Library for Java

As the name already suggests, the first library is specifically developed for the Android platform. Its focus is on enabling you to incorporate video playback functionality into an app by providing a player framework. If your goal is to enable users to simply play YouTube videos, then is probably easiest to implement. Do note that this library requires the official YouTube app to be installed on the device.

The second library is more generic (although there are separate instructions for using it on Android) and provides a wrapper around YouTube's Data API to make interfacing with it a little easier. Hence, it allows you to do basically everything you can also do with the web API. As such, it solves a different problem than the Android Player API and is more likely the way to go if you want full control over how you display video data in your own UI.

Your third option would be to do exactly what you did for your web-based solution: make the API call yourself, parse the response and bind up the relevant data to your UI components. Various networking libraries (i.e. Retrofit) can greatly simplify this process.




回答2:


Refer my post here. I just tried this method for my project and it works very nicely. You don't need the above code or any google api jar imports. Just replace the HTTP request with your HTTP request.

Output is returned in JSON, for which you can use a JSON parser jar to retrieve the title,thumbnails and other details you may require, as I have described in my answer there.




回答3:


Try this:

protected void requestYoutubeVideos(String text) {
      try {
          youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
              public void initialize(HttpRequest request) throws IOException {
              }
          }).setApplicationName("My app name").build();

          // Define the API request for retrieving search results.
          YouTube.Search.List query = youtube.search().list("id");

          // Set your developer key from the Google Cloud Console for
          // non-authenticated requests. See:
          // https://cloud.google.com/console
          query.setKey(YOUTUBE_API_KEY);
          query.setQ(text);
          query.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);

          // To increase efficiency, only retrieve the fields that the
          // application uses.
          query.setFields("items(id)");
          query.setOrder("viewCount");

          // Restrict the search results to only include videos. See:
          // https://developers.google.com/youtube/v3/docs/search/list#type
          query.setType("video");

          SearchListResponse searchResponse = query.execute();
          List<SearchResult> list = searchResponse.getItems();
          Log.e("Youtube search", "list ===> " + list);

          //Get Info for each video id
          for (SearchResult video: list) {
              youtubeList.add(video);

              YouTube.Videos.List query2 = youtube.videos().list("id,contentDetails,snippet,statistics").setId(video.getId().getVideoId());
              query2.setKey(YOUTUBE_API_KEY);
              query2.setMaxResults((long) 1);
              query2.setFields("items(id,contentDetails,snippet,statistics)");

              VideoListResponse searchResponse2 = query2.execute();
              List<Video> listEachVideo = searchResponse2.getItems();
              Video eachVideo = listEachVideo.get(0);

          }

      } catch (GoogleJsonResponseException e) {
          Log.e("Youtube search", "There was a service error: " + e.getDetails().getCode() + " : "
                  + e.getDetails().getMessage());
      } catch (IOException e) {
          Log.e("Youtube search", "There was an IO error: " + e.getCause() + " : " + e.getMessage());
      } catch (Throwable t) {
          t.printStackTrace();
      }
  }

and do not forget to call it from another thread:

 new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            requestYoutubeVideos("Harry el Sucio Potter");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}).start();


来源:https://stackoverflow.com/questions/33969507/how-to-retrieve-details-of-single-video-from-youtube-using-videoid-through-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!