这是我从 Youtube 获取频道列表的代码,希望对您有所帮助
public void getYouTubeData(){
StringBuilder urlString = new StringBuilder();
HttpURLConnection urlConnection = null;
URL url = null;
urlString.append("http://gdata.youtube.com/feeds/api/users/CaliforniaDMV/playlists?v=2&alt=json");
m_ytdata = new ArrayList<YoutubeChannelList.YouTubePlayListData>();
try {
url = new URL(urlString.toString());
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
urlConnection.setRequestMethod("GET");
} catch (ProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
try {
urlConnection.connect();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
InputStream inputStream = null;
try {
inputStream = urlConnection.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = null;
if(inputStream != null){
result = convertStreamToString(inputStream);
} else {
Log.d("NULLLL","NULL");
}
try {
inputStream.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
urlConnection.disconnect();
try {
final JSONObject json = new JSONObject(result);
final JSONObject jsonentry = json.getJSONObject("feed");
int length = jsonentry.length();
//final JSONObject jsonarr = jsonentry.getJSONObject("entry")
final JSONArray jsonarr = jsonentry.getJSONArray("entry");
int len = jsonarr.length();
//Log.d("XXX", "Length is " + length + "arry len: " + len);
for(int loop = 0;loop<len;loop++){
YouTubePlayListData yt = new YouTubePlayListData();
final JSONObject inner = jsonarr.getJSONObject(loop);
yt.setIds(inner.getJSONObject("yt$playlistId").getString("$t"));
//yt.setVideoId(getThumbnailImage(inner.getJSONObject("yt$playlistId").getString("$t")));
yt.setUpdated(inner.getJSONObject("updated").getString("$t").substring(0,10));
yt.setTitles(inner.getJSONObject("title").getString("$t"));
yt.setCount(Integer.parseInt(inner.getJSONObject("yt$countHint").getString("$t")));
//Log.d("LOOP","id: " +inner.getJSONObject("yt$playlistId").getString("$t"));
//Log.d("LOOP","updated: " + inner.getJSONObject("updated").toString());
//Log.d("LOOP","title: " + inner.getJSONObject("title").getString("$t"));
m_ytdata.add(yt);
}
runOnUiThread(returnRes);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}