Wednesday, April 13, 2011

JSON via Http on Android

There are many ways to handle JSON data on android. Here is my way to do that.
In this tutorial, I am going to get external JSON data with some Http post request and response.

First, let's create the class that will handle the incoming and outgoing data.
public class HttpUtils {
 private static final String URL = "http://path/to/php/script.php";

 public static String doRequest(String username, String password) {
  HttpClient client = new DefaultHttpClient();
  HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
  JSONObject jsonObject = new JSONObject();
  HttpPost post;
  HttpResponse response;
  String responseStr = "[{}]";
  try {
   post = new HttpPost(URL);
   Log.i("Http", "Requesting " + URL);
   
   //Puting the username and password as JSON data
   jsonObject.put("username", username);
   jsonObject.put("password", password);
   StringEntity se = new StringEntity("JSON=" + jsonObject.toString());
   se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/x-www-form-urlencoded"));
   post.setEntity(se);
   Log.i("Http", "Sending :" + slurp(post.getEntity().getContent()));
   response = client.execute(post);

   // Checking response
   if (response.getStatusLine().getStatusCode() == 200) {
    // Get the data in the entity
    InputStream in = response.getEntity().getContent();
    responseStr = slurp(in);
    Log.i("Http", "Getting :" + responseStr);
   } else {
    throw new HttpException("HttpMethod Returned Status Code: "
      + response.getStatusLine().getStatusCode()
      + " when attempting: " + URL);
   }
  } catch (Exception e) {
   Log.e("Http", e.getMessage(), e.fillInStackTrace());
  }

  return responseStr;
 }

 /**
  * Convert an InputStream to String
  * 
  * @param in the InputStream to be converted to String
  * @return the result string
  * @throws IOException
  */
 private static String slurp(InputStream in) throws IOException {
  StringBuffer out = new StringBuffer();
  byte[] b = new byte[4096];
  for (int n; (n = in.read(b)) != -1;) {
   out.append(new String(b, 0, n));
  }
  return out.toString();
 }
}
As you can see, we used a JSONObject to post some data to our php script witch look like this :
if (isset($_POST['JSON'])) {
    header('Content-Type: application/json; charset=iso-8859-1');
    $data = json_decode($_POST['JSON'], true);
    $username = $data['username'];
    $password = $data['password'];
    if ($username == 'ElWardi' && $password == 'json') {
        $response = array(
            array('success' => true),
            array('name' => 'PFA', 'description' => 'PFA test'),
            array('name' => 'PFA1', 'description' => 'PFA1 test'),
            array('name' => 'PFA2', 'description' => 'PFA2 test'),
            array('name' => 'PFA3', 'description' => 'PFA3 test'),
            array('name' => 'PFA4', 'description' => 'PFA4 test')
        );
    } else {
        $response = array(
            array('success' => false)
        );
    }
    print_r(json_encode($response));
}
[Update] : The php script will encode an array of data and send it back to the android application. The encoded data will look like this :
[{"success":true},
{"name":"PFA","description":"PFA test"},
{"name":"PFA1","description":"PFA1 test"},
{"name":"PFA2","description":"PFA2 test"},
{"name":"PFA3","description":"PFA3 test"},
{"name":"PFA4","description":"PFA4 test"}]
Now, all the rest to do is call the doRequest method then parse the response data. I made that in the MainActivity.java :
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        String response = HttpUtils.doRequest("ElWardi", "json");
  JSONArray json;
  try {
   /*
    *  Build the JSAONArray from a string
    */
   json = new JSONArray(response);
   Log.i("JSON", "Number of data fetched : " + json.length()); // data count
   /*
    * get the data from the JSONArray if the authentifcation data are valid
    */
   if (json.optJSONObject(0).getBoolean("success")) {
    for (int i = 1; i < json.length(); i++) {
     Log.i("MyData", "Name : " + json.optJSONObject(i).getString("name")
       + "Description : " + json.optJSONObject(i).getString("description"));
    }
   }else 
    Log.e("MyData", "Some entered data (username or password) are invalid"); 
  } catch (JSONException e) {
   Log.e("JSON", e.getMessage(), e.fillInStackTrace());
  }
    }
}
You can see the results on the LogCat or any other debugging tool you use.
Well, I guess this will be all for my first blog here, I hope you will find it quite useful :).
Feel Free to leave your comments :)

1 comment: