【ANDROID】如何從YouTube獲取播放列表視訊

2021-02-02 ANDROID

我正在編寫一個要在其中獲取YouTube視訊列表的應用程式,並且可以通過使用特定使用者的帳戶(例如以下連結)來做到這一點:

 HttpUriRequest request = new HttpGet("http://gdata.youtube.com/feeds/api/users/GoogleDevelopers/uploads?v=2&alt=jsonc");

但是,如果我想使用播放列表來獲取YouTube視訊的列表,那麼我需要對程式碼進行哪些更改,例如在這裡,我不需要使用者名稱即可提取視訊。
  http://gdata.youtube.com/feeds/api/playlists/PL1D5B07DD840FB46D?v=2&alt=json

原始連結:http://www.youtube.com/playlist?list=PL1D5B07DD840FB46D

我的程式碼:
  public class GetYouTubeUserVideosTask implements Runnable {

public static final String LIBRARY = "Library";
private final Handler replyTo;
private final String username;

public GetYouTubeUserVideosTask(Handler replyTo, String username) {
    this.replyTo = replyTo;
    this.username = username;
}

@Override
public void run() {
    try {

        HttpClient client = new DefaultHttpClient();
        HttpUriRequest request = new HttpGet("http://gdata.youtube.com/feeds/api/playlists/PL1D5B07DD840FB46D?v=2&alt=json");   
        HttpResponse response = client.execute(request);
        String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
        JSONObject json = new JSONObject(jsonString);
        JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
        List<Video> videos = new ArrayList<Video>();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String title = jsonObject.getString("title");
            String url;
            try {
                url = jsonObject.getJSONObject("player").getString("default");
            } catch (JSONException ignore) {
                url = jsonObject.getJSONObject("player").getString("default");
            }

            String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault"); 
            videos.add(new Video(title, url, thumbUrl));
        }       
        Library lib = new Library(username, videos);

        Bundle data = new Bundle();
        data.putSerializable(LIBRARY, lib);

        Message msg = Message.obtain();
        msg.setData(data);
        replyTo.sendMessage(msg);

    } catch (ClientProtocolException e) {
        Log.e("Feck", e);
    } catch (IOException e) {
        Log.e("Feck", e);
    } catch (JSONException e) {
        Log.e("Feck", e);
    }
}
   }

解決辦法

您可以使用新的YouTube資料API v3來獲取播放列表:

https://developers.google.com/youtube/v3/docs/playlists

在我寫的本教程中(西類牙語..但您可以看到程式碼更改..):

http://fuse21.blogspot.com.ar/2013/01/utilizando-youtube-data-api-v3-desde.html

我展示瞭如何更改官方示例“tasks-android-sample”:

http://code.google.com/p/google-api-java-client/source/browse/tasks-android-sample/?repo=samples

使用YouTube資料API而不是任務API。

文章參考: https://stackoverflow.com/questions/14292325/

出處

Have any Question?

Let us answer it!