Making use of Youtube DATA API to retrieve video details in android app based on keyword

∥☆過路亽.° 提交于 2019-12-09 01:57:38

问题


I have extensively tried to Making use of Youtube DATA API to retrieve youtube video details in android app based on keyword, by downloading the example here.

It leads to lot of import complexities,conflicts and duplicate dexing as described in my question here.

Is there a simpler way to do this using Java for an android app?


回答1:


Yes there is!!

You can just make a simple GET HTTP request to youtube based on the examples they have listed in the documenation here. This does not require any google api JAR downloads.

Code example :

MakeHTTPRequest makeHTTPRequest = new MakeHTTPRequest();
    String response = "";
    String apiKey = MY_KEY; //Set your Android Key here

    String query = "";
    // input = input.replace(",","+");
    if(input.contains(" "))
        query = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=%22"+input.replace(" ","+")+"%22&type=video&key="+apiKey;
    else
        query = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=%22="+input+"%22&type=video&key="+apiKey;
    try {
        response = makeHTTPRequest.sendGet(query);
    }
    catch (Exception e){
        e.printStackTrace();
    }

    System.out.println("Youtube results : "+response);

    JSONObject responseJSON= null;
    try {
        responseJSON = new JSONObject(response);

        JSONArray items = responseJSON.getJSONArray("items");


        for(int i=0;i<items.length();i++){
            System.out.println("Item "+i+" : ");
            System.out.println("Title : "+items.getJSONObject(i).getJSONObject("snippet").get("title"));
            System.out.println("Description : "+items.getJSONObject(i).getJSONObject("snippet").get("description"));
            System.out.println("URL : https://www.youtube.com/watch?v="+items.getJSONObject(i).getJSONObject("id").getString("videoId"));



        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

Additional things needed:

  1. Get your API_KEY.

  2. You will need to download the org.json jar or any other supporting jar for JSON parsing the output.

  3. You also need to include the code here on How to send HTTP request GET/POST in Java.

EDIT 1: Remove videoCaption parameter to get matching results with Youtube website.

EDIT 2: If you want to search for say a phrase spice boat then input should be enclosed in quotes, that is, variable

input = "%22spice+boat%22";

Then the search is truely accurate.



来源:https://stackoverflow.com/questions/33982758/making-use-of-youtube-data-api-to-retrieve-video-details-in-android-app-based-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!