package com.ved.musicmapapp.youtube; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.params.ClientPNames; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.ved.musicmapapp.utils.DeveloperKey; import android.util.Log; public class YouTube { public ArrayList<Video> getVideos(String username) throws YouTubeException { String rawJSON = fetchJSON(username); ArrayList<Video> videos; try { JSONObject resultSet = new JSONObject(rawJSON); JSONArray results = resultSet.getJSONArray("items"); videos = new ArrayList<Video>(results.length()); if(results.length()>1) { videos.add(new Video(results.getJSONObject(0))); } } catch(JSONException e) { throw new YouTubeException(e); } return videos; } private String fetchJSON(String username) throws YouTubeException { String url = null; try { String temp = URLEncoder.encode(username.trim(), "UTF-8"); url = feedUrl(temp); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); try{ HttpGet httpGet = new HttpGet(url); httpGet.setHeader("User-Agent", "Android"); httpGet.setHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"); System.out.println("final url : "+url); httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); HttpResponse response = httpClient.execute(httpGet,localContext); String text = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); return text; } catch(Exception e){ e.printStackTrace(); throw new YouTubeException(e); } } private String feedUrl(String username) { Log.e("check","url///"+"https://www.googleapis.com/youtube/v3/search?part=snippet&q="+username+"&type=video&key="+DeveloperKey.DEVELOPER_KEY); return "https://www.googleapis.com/youtube/v3/search?part=snippet&q="+username+"&type=video&key="+DeveloperKey.DEVELOPER_KEY; } }