1
这是我在这里看到的一个代码,它使用视频ID从youtube获取单个视频的数据。但是,我似乎无法从URL中获得“标题”。它在我的浏览器中工作,但在我正在开发的android应用程序中,它没有。代码有什么问题?如何从此API提取“标题”?
private class RequestTask extends AsyncTask<String, String, String> {
// make a request to the specified url
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
// convert the String response to a JSON object
JSONObject jsonResponse = new JSONObject(response);
Toast.makeText(getActivity(), jsonResponse.getString("title"), Toast.LENGTH_SHORT).show();
// fetch the array of movies in the response
JSONArray jArray = jsonResponse.getJSONArray("movies");
} catch (JSONException e) {
Log.d("Test", "Couldn't successfully parse the JSON response!");
}
}
}
这里顺便API,
https://www.googleapis.com/youtube/v3/videos?id=P3mAtvs5Elc&key=<INSERT_API_SERVER_KEY_HERE>&fields=items(id,snippet(description,channelId,title,categoryId),statistics)&part=snippet,statistics
而不是'jsonResponse.getString(“title”)'尝试使用'js onResponse.getJSONObject( “标题”)。的toString()'。 –
将您的回复记录为日志。发布您收到的回复或异常。 –