This example will allow a Android application to connect to a web service that serves JSON objects/arrays. This example has been derived from the RESTful example posted here.
This app will connect to a web page/site/service located – http://rentopoly.com/ajax.php?query=Bo and returns a JSONArray of towns/cities and universities that match the supplied query. This service produces the following output;
// {"query":"Bo","suggestions":["Bognor Regis","Bolton","Bournemouth","Camborne","Eastbourne","Loughborough","Peterborough","Scarborough","University of Bolton","Boston University","Bournemouth University","Camborne School of Mines","Loughborough University","Ravensbourne College of Design and Communication","University of Hull (Scarborough Campus)"]}
Now to explain how it all works.
When the application loads it creates the layout and textview component. It then sets the text of the textview by calling connect() function. This function returns a string.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
txt.setText(connect("http://rentopoly.com/ajax.php?query=Bo"));
}
The connect function will accept a string as a url and create a HttpClient object;
private String connect(String url){
// Create the httpclient
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Declare a response
HttpResponse response;
// Declare a return string
String returnString = null;
.....
From the partial code listing above, the function accepts a URL as a string, create the HttpClient (used to fetch the webpage), delcares a HttpResponse (for the response) and String (which will be returned as the result of this function). The HttpResonse will contain the response including headers such as 200 for ok, 301 for redirect and 404 for file not found. In this example we will only focus on the 200 response.
Next part of the connect function is to open the webpage (execute), check the status of the response and check the body contains text.
try {
// Open the webpage.
response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode() == 200){
// Connection was established. Get the content.
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
....
The next part is to convert the InputStream into a string. This uses the convertStreamToString function which was found from the RESTful example noted earlier.
At the same time, the string will be converted into a new JSONObject (jsonResponse). The follwoing code shows how this is done…
// Load the requested page converted to a string into a JSONObject.
JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
// Get the query value'
String query = jsonResponse.getString("query");
// Make array of the suggestions
JSONArray suggestions = jsonResponse.getJSONArray("suggestions");
// Build the return string.
returnString = "Found: " + suggestions.length() + " locations for " + query;
for (int i = 0; i < suggestions.length(); i++) {
returnString += "\n\t" + suggestions.getString(i);
}
// Cose the stream.
instream.close();
....
The above code has create the JSONObject from the string. Now to make this object into somethnig meaning full that can be returned. The first step creates a String named query which will contain the string named “query” from within the JSONObject. In this case this would be “Bo”.
The next step is to get the available suggestions in the object and convert them into a new Array. This is done by calling the getJSONArray() method suplying the “suggestions” as the key.
Now we have an array, its a simple case of looping through and making a nice string.
The last part is to close the inputstream by calling the close() method to free up resources and return the string created. There are a couple of catch blocks which will catch exceptions raised by the JSONObject or HttpClient.
}
}
else {
// code here for a response othet than 200. A response 200 means the webpage was ok
// Other codes include 404 - not found, 301 - redirect etc...
// Display the response line.
returnString = "Unable to load page - " + response.getStatusLine();
}
}
catch (IOException ex) {
// thrown by line 80 - getContent();
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
catch (JSONException ex){
// JSON errors
returnString = "JSON failed; " + ex.getMessage();
}
return returnString;
}
The complete class source code follows;
/**
* Modified example taken from
* http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
*
* This class will connect to a website, get a JSON Object and display results into a textview.
* @author Damon Skelhorn - eighty-six.co.uk
*/
package com.damon86.httpdownload;
import java.io.InputStream;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Httpdwld extends Activity {
/** Called when the activity is first created. */
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
txt.setText(connect("http://rentopoly.com/ajax.php?query=Bo"));
}
private String connect(String url){
// Create the httpclient
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
// return string
String returnString = null;
try {
// Open the webpage.
response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode() == 200){
// Connection was established. Get the content.
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
// Load the requested page converted to a string into a JSONObject.
JSONObject myAwway = new JSONObject(convertStreamToString(instream));
// Get the query value'
String query = myAwway.getString("query");
// Make array of the suggestions
JSONArray suggestions = myAwway.getJSONArray("suggestions");
// Build the return string.
returnString = "Found: " + suggestions.length() + " locations for " + query;
for (int i = 0; i < suggestions.length(); i++) {
returnString += "\n\t" + suggestions.getString(i);
}
// Cose the stream.
instream.close();
}
}
else {
// code here for a response othet than 200. A response 200 means the webpage was ok
// Other codes include 404 - not found, 301 - redirect etc...
// Display the response line.
returnString = "Unable to load page - " + response.getStatusLine();
}
}
catch (IOException ex) {
// thrown by line 80 - getContent();
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
catch (JSONException ex){
// JSON errors
returnString = "JSON failed; " + ex.getMessage();
}
return returnString;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
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) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}

