Hi, Thank you guys for telling me how I want to fall. I finally came up with something and also wanted to share my experience.
According to youtube we can request data as xml or json. I used json method for my implementation
http://gdata.youtube.com/feeds/api/videos?q=title_you_want_to_search&max-results=1&v=2&alt=jsonc
you can get more information from the youtube developer guide
above, the query "title_you_want_to_search" is the keyword you want to find. and we can customize the result by passing additional parameters to the URL.
- "max-results": indicate how many results you want to get (in my case, I just want only one)
- "alt": desired json or xml result format
First we need to request data from the Youtube api, and then we must choose which part of the information we want to select from the array. In my case, I used "data" and "elements" to get a video game. after we turn on the video, then we can make the video URL as follows
String mVideoLink = "https://youtu.be/"+videoID; (I used the following functions to do this)
public String readYoutubeFeed(String songTitle) { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); String url = "http://gdata.youtube.com/feeds/api/videos?q="+songTitle+"&max-results=1&v=2&alt=jsonc"; try { URLEncoder.encode(url, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); Log.v(TAG,"encode error"); } HttpGet httpGet = new HttpGet(url); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content, "UTF-8")); String line; while ((line = reader.readLine()) != null) { builder.append(line); } } else { Log.v(TAG,"Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); Log.v(TAG,"readYoutubeFeed exeption1"); } catch (IOException e) { e.printStackTrace(); Log.v(TAG,"readYoutubeFeed exeption2"); } return builder.toString(); } public String getYouTubeVideoId(String songTitle){ String jesonData = readYoutubeFeed(songTitle); Log.i(TAG,jesonData); String title = "123"; try { SONObject jObj = new JSONObject(jesonData); JSONArray ja = jObj.getJSONObject("data").getJSONArray("items"); JSONObject jo = (JSONObject) ja.get(0); title = jo.getString("id"); Log.v(TAG,"id is " +title); } catch (Exception e) { e.printStackTrace(); Log.v(TAG,"error occerd"); } return title;
}
One important thing to mention in this conversion of strings to "UTF-8" is that creating JsonArray may be an exception to the exception. Maybe there are better ways to do this. If there is an offer
source share