如何使用Android中的youtube数据API搜索视频

时间:2014-02-20 16:43:23

标签: android youtube youtube-api android-youtube-api

我正在Android中开发一个应用程序,需要通过关键字搜索YouTube的视频。我使用了Youtube数据API,代码如下:

    try {
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("YoutubeQoE").build();

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

        // Set your developer key from the Google Cloud Console for
        // non-authenticated requests. See:
        // https://cloud.google.com/console
        search.setKey(DeveloperKey.DEVELOPER_KEY);
        search.setQ("dogs");

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

        // To increase efficiency, only retrieve the fields that the
        // application uses.
        //search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(25);

        SearchListResponse searchResponse = search.execute();
        List<SearchResult> lista = searchResponse.getItems();

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

对于de DEVELOPER_KEY,我在google开发者控制台上使用了公共API访问。

但是当我执行程序时,行中存在问题:

SearchListResponse searchResponse = search.execute();

在android manifest.xml中我有这些权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

如果有人能帮助我,我将非常感激

3 个答案:

答案 0 :(得分:12)

实现这一目标的另一种方法是从中获得结果:

https://www.googleapis.com/youtube/v3/search?part=snippet&q=eminem&type=video&key=<key>

您可以使用参数来获得实际需要的内容。您还需要https://console.developers.google.com/的API密钥。

答案 1 :(得分:2)

您可以将项目与YouTube Direct Lite for Android进行比较。是的,而不是OAuth2,设置API密钥就足够了。

答案 2 :(得分:0)

通常,当有人尝试在UI线程上执行网络调用时会发生此错误,而Android不允许这样做。 如果遇到此错误,请检查logcat-(error-android-os-networkonmainthreadexception) 请通过以下答案来解决此问题-fix of neworkonmainthreadexception