我正在尝试向 youtube 创建一个请求并尝试解析我得到的 json-c 结果。代码不工作并抛出异常。我哪里错了?请帮助
MainActivity.java
try{
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&category=autos&max-results=1&orderby=relevance&q="+searchTerm);
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
JSONObject jsonObject = jsonArray.getJSONObject(0);
String title = jsonObject.getString("title");
Toast.makeText(getApplicationContext(), title, Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Log.d("YOUTUBE", e.getMessage());
}
StreamUtils.java
public class StreamUtils {
public static String convertToString(InputStream inputStream) throws IOException {
if (inputStream != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 1024);
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
inputStream.close();
}
return writer.toString();
} else {
return "";
}
}
}
LOGCAT 的输出
01-06 21:15:00.328: E/AndroidRuntime(810): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.allinonedata/com.example.allinonedata.MainActivity}: java.lang.NullPointerException: println needs a message
01-06 21:15:00.328: E/AndroidRuntime(810): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)