首页 > 解决方案 > 未从 youtube 数据 api 获得响应

问题描述

我是 android 新手,我正在尝试在我的 android 应用程序中实现 YouTube 的关键字搜索。但我无法从 API 获得响应(我认为)。我认为 search.execute() 中存在一些问题。我看了也有一些其他的答案,但无法找到任何解决方案。

这是课程(我对其进行了一些修改):

class Search {



                private static final long NUMBER_OF_VIDEOS_RETURNED = 2;

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

                /**
                 * Initialize a YouTube object to search for videos on YouTube. Then
                 * display the name and thumbnail image of each video in the result set.
                 *
                 *
                 */
                private  void Hakuna() {
                    // Read the developer key from the properties file.


                    try {
                        // This object is used to make YouTube Data API requests. The last
                        // argument is required, but since 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(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
                            public void initialize(HttpRequest request) throws IOException {
                            }
                        }).setApplicationName("youtube-cmdline-search-sample").build();

                        // Prompt the user to enter a query term.
                        String queryTerm = getInputQuery();

                        // 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 }}
                        String apiKey = "HERE_I_PUT_MY_APIKEY";

                        search.setKey(apiKey);
                        search.setQ(queryTerm);

                        // 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(NUMBER_OF_VIDEOS_RETURNED);

                        // Call the API and print results.
                        SearchListResponse searchResponse = search.execute();
                        mResult.setText("hello");
                        List<SearchResult> searchResultList = searchResponse.getItems();

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

                /*
                 * Prompt the user to enter a query term and return the user-specified term.
                 */
                private  String getInputQuery() throws IOException {

                    String inputQuery = "";


                    inputQuery = mSearchtext.getText().toString();

                    if (inputQuery.length() < 1) {
                        // Use the string "YouTube Developers Live" as a default.
                        inputQuery = "YouTube Developers Live";
                    }
                    return inputQuery;
                }

                /*
                 * Prints out all results in the Iterator. For each result, print the
                 * title, video ID, and thumbnail.
                 *
                 * @param iteratorSearchResults Iterator of SearchResults to print
                 *
                 * @param query Search query (String)
                 */
                private  void prettyPrint(Iterator<SearchResult> iteratorSearchResults, String query) {
                    mResult.setText("hello");
                    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();

                        // Confirm that the result represents a video. Otherwise, the
                        // item will not contain a video ID.
                        if (rId.getKind().equals("youtube#video")) {
                            Thumbnail thumbnail = singleVideo.getSnippet().getThumbnails().getDefault();

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

这是我添加的依赖项:

implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.google.apis:google-api-services-youtube:v3-rev181-1.22.0'

可能有一些多余的代码行,请忽略它们。

标签: androidyoutube-api

解决方案


推荐阅读