2014-02-20 60 views
7

我正在開發一款Android應用程序,需要通過關鍵字搜索YouTube的視頻。我已經使用YouTube數據API與下面的代碼:如何在Android中使用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(); 
    } 

對於德Developer_Key開發我已經使用在谷歌開發者控制檯公共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" /> 

我會很感激,如果有人可以幫助我

+0

你得到的錯誤是什麼? –

+0

親愛的Josesvm,我正在做同樣的嘗試。但是我無法獲得這個搜索java類文件的支持庫。所以請分享jar文件或jar文件的位置。 –

回答

2

您可以針對YouTube Direct Lite for Android比較項目。是的,而不是OAuth2,設置API密鑰就足夠了。

從這個
+0

非常感謝。我發現你的幫助存在問題。雖然我在Android應用程序中使用它,但我應該爲Web瀏覽器使用API​​密鑰。 – josesvm

+0

你有其他的例子,或者它只是youtube直接精簡版 –

12

實現這一目標的另一種方式會得到結果:

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

可以用參數打得到你的實際需要。您還需要一個來自https://console.developers.google.com/的API密鑰。

+0

你能解釋這一點嗎?我試圖通過輸入搜索關鍵詞使用google youtube api v3 .so我得使用谷歌https提供的示例代碼:/ /developers.google.com/youtube/v3/code_samples/java#search_by_keyword。但我無法獲得此示例類的支持jar文件。因此,請告訴建議。 –

相關問題