I am pretty new to the world of Android and Java and I am wondering how I get data from the web api here http://www.imdbapi.com/ Into android. Should I use JSON or XML? What are the steps? Firstly I want to know how to download the data and then how to parse it to variables. Any sample code?
1 Answer
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
JSONArray arr = new JSONArray();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == 200) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
arr=new JSONArray(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.e(TAG,e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG,e.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e(TAG,e.toString());
}
return arr;
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Log.e(TAG + "ERROR",e.toString());
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG + "ERRO",e.toString());
}
}
return sb.toString();
}
As for parsing, here you go: http://developer.android.com/reference/org/json/package-summary.html
btw, this was all easily found on google : )
3 Comments
saber tabatabaee yazdi
this run in 14 sdk version? what i do if want to run on 2.3.3? instead of json which alternative way to get those parameters?
Shivam
This code throws error at TAG in android studio.
'TAG' has private access in 'android.support.v4.app.Fragment'IamAlexAlright
You can just remove TAG ... I throw it in the log so I know exactly where the exception is coming from.