Jalaj Chawla Jalaj Chawla - 3 years ago 121
JSON Question

Unable to retrieve VideoMetaData such as duration of video and stream url using playlist Items API?

Problem Statement

1)I am a beginner at implementing youtube api and I want to retrieve VideoMetaData such as duration of video and stream url.

MyAnalysis :

1)I have used the youtube api to retrieve this metaData such as Video Tilte,VideoID and creation Date.

2)The problem is I am not able to see other data such as Video duration and stream url in the Response.

//Also,StartTime and EndTime has been depreciated.So I cannot find duration


Then,how can I fetch these details related to video.


Below is the response I am getting.

https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlistItems.list?part=snippet%252CcontentDetails&maxResults=25&playlistId=PL8WtjSOdakGuBu0q9EKLXndc4jcAQxs2Y&_h=1&

Code for the Same :

public class Search1 {
private static YouTube.PlaylistItems.List playlistItemRequest;
private static String PLAYLIST_ID = "PL8WtjSOdakGuBu0q9EKLXndc4jcAQxs2Y";
private static final Long NUMBER_OF_VIDEOS_RETURNED = (long) 10;
private static String apiKey="AIzaSyDJAaPLW5wbWdfKX6CjfvSo5yrF3K3rlwc";
private static YouTube youtube;

public static void main(String s[]){
youtube = new YouTube.Builder(new NetHttpTransport(),
new JacksonFactory(), new HttpRequestInitializer()
{
@Override
public void initialize(HttpRequest hr) throws IOException {}
}).setApplicationName("youtube-cmdline-search-sample").build();
List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
try
{
playlistItemRequest = youtube.playlistItems().list("snippet,contentDetails");
playlistItemRequest.setPlaylistId(PLAYLIST_ID);
playlistItemRequest.setFields("items(snippet/title,snippet/playlistId,snippet/publishedAt,snippet/description,snippet/thumbnails/default/url,contentDetails/videoId,contentDetails/startAt,contentDetails/endAt,contentDetails/videoPublishedAt),nextPageToken,pageInfo");
playlistItemRequest.setKey(apiKey);
// videoItem.setId(item.getContentDetails().getVideoId());

String nextToken = "";
do {
playlistItemRequest.setPageToken(nextToken);
PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();

playlistItemList.addAll(playlistItemResult.getItems());

nextToken = playlistItemResult.getNextPageToken();
} while (nextToken != null);
}catch(IOException e)
{
System.out.println("Exception"+e);
}
Iterator iteratorSearchResults=playlistItemList.iterator();
while (iteratorSearchResults.hasNext()) {

PlaylistItem playlist = (PlaylistItem) iteratorSearchResults.next();
// String duration=(playlist.getContentDetails().getStartAt()-playlist.getContentDetails().getEndAt());
System.out.println(" Title: " + playlist.getSnippet().getTitle());
System.out.println(" Video Created Date" + playlist.getContentDetails().getVideoPublishedAt());

System.out.println(" PlayList ID: " + playlist.getSnippet().getPlaylistId());
System.out.println(" Video ID: " + playlist.getContentDetails().getVideoId());

System.out.println(" Stream url of PlayList: ");
System.out.println(" Start Time: " + playlist.getContentDetails().getStartAt());
System.out.println(" End Time: " + playlist.getContentDetails().getEndAt());
System.out.println(" Duration " );

}
}
}

Answer Source

I used th following changes in the Code to access Video MetaData

1)Change was done to retrieve url where I concatinated the url along with videoId

2)Made a Connection with youtube api again to retrieve video metadata

public static final MediaType JSON= MediaType.parse("application/json; charset=utf-8");
static String url="http://eventapi-dev.wynk.in/tv/events/v1/event";
static OkHttpClient client = new OkHttpClient();
private static YouTube.PlaylistItems.List playlistItemRequest;
private static String PLAYLIST_ID = "PL8WtjSOdakGuBu0q9EKLXndc4jcAQxs2Y";
private static String apiKey="AIzaSyDJAaPLW5wbWdfKX6CjfvSo5yrF3K3rlwc";
private static YouTube youtube;
public static void main(String s[]) throws IOException {
        //Create a Bean 
        WynkData wd=new WynkData(); 
        String videoID=null;

        //Make a Connection with YouTubeApi 
        youtube = new YouTube.Builder(new NetHttpTransport(),
        new JacksonFactory(), new HttpRequestInitializer()
        {
            @Override
            public void initialize(HttpRequest hr) throws IOException {}
            }).setApplicationName("youtube-cmdline-search-sample").build();
        List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
        try
        {
            //Specify the search Params
            playlistItemRequest = youtube.playlistItems().list("snippet,contentDetails");
            playlistItemRequest.setPlaylistId(PLAYLIST_ID);
            playlistItemRequest.setFields("items(snippet/title,snippet/playlistId,snippet/publishedAt,contentDetails/videoId,contentDetails/videoPublishedAt),nextPageToken,pageInfo");
            playlistItemRequest.setKey(apiKey);

            String nextToken = "";
            do 
            {
//                  Execute and add in a list
                playlistItemRequest.setPageToken(nextToken);
                PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();
                playlistItemList.addAll(playlistItemResult.getItems());
                nextToken = playlistItemResult.getNextPageToken();
            }while (nextToken != null);
        }
        catch(IOException e)
        {
            System.out.println("Exception"+e);
        }

//          Retrieve the Recods
        Iterator<PlaylistItem> iteratorSearchResults=playlistItemList.iterator();
        while (iteratorSearchResults.hasNext()) {
        PlaylistItem playlist =  (PlaylistItem) iteratorSearchResults.next();
        wd.setTitle(playlist.getSnippet().getTitle());
        System.out.println(" Title: " + playlist.getSnippet().getTitle());
        System.out.println(" Video Created Date" + playlist.getContentDetails().getVideoPublishedAt());
        wd.setCreatedDate(playlist.getContentDetails().getVideoPublishedAt());

//Change1

 System.out.println("Video Url https://www.youtube.com/watch?v="+playlist.getContentDetails().getVideoId());
        videoID=playlist.getContentDetails().getVideoId();
        System.out.println(" Stream url of PlayList: ");
        String streamurl="https://www.youtube.com/watch?v="+videoID;
        wd.setStreamurl(streamurl);
        System.out.println(" PlayList ID: " + playlist.getSnippet().getPlaylistId());
        System.out.println(" Video ID: " + playlist.getContentDetails().getVideoId());
        }

Change2

//          Make a Connection with YouTube Api again to retrieve Video Duration
        System.out.println(videoID);

        final String videoId = videoID;
        YouTube.Videos.List videoRequest = youtube.videos().list("snippet,statistics,contentDetails");
        videoRequest.setId(videoId);
        videoRequest.setKey(apiKey);
        VideoListResponse listResponse = videoRequest.execute();
        List<Video> videoList = listResponse.getItems();

        Video targetVideo = videoList.iterator().next();
        System.out.println(targetVideo.getSnippet().getTitle());
        System.out.println(targetVideo.getStatistics().getViewCount());
        String duration=targetVideo.getContentDetails().getDuration();
        StringBuilder sb=new StringBuilder(duration);
        duration=sb.substring(2).replaceAll("[A-Z]",":").toString();
        wd.setDuration(duration);
        System.out.println(wd);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download