Sending JSON Data From Android to a PHP Script

In my previous blog Meet JSON! I talked about how JSON is used in the mainstream. Now, how do we send JSON Objects from Android to a server script written in PHP?

In this tutorial we will pass a JSONObject with our message to our server code written in PHP. Our server reads our JSON, reverse our message, and send it as a reply. I will not be discussing in detail the server code, and the java client code (MainActivity.java) for these are not my main topic in this Blog. I will be merely give emphasis on “Sending” the data.

PHP

Our server code

<?php 

if( isset($_POST["json"]) ) {
     $data = json_decode($_POST["json"]);
     $data->msg = strrev($data->msg);

     echo json_encode($data);

}

For those who don’t understand these lines of PHP code, in our first line we’re saying that if $_POST[“json”] has a value, then we execute. You may want to read about Server and Request variables in PHP. In the next line, we decode the json data inside $_POST[“json”] and catch it. Reverse the String in the “msg” entity of the object, encode and echo.

Our MainActivity.java (ANDROID)

package com.coffeecodes.coffecodesdoodle;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
			JSONObject toSend = new JSONObject();
			toSend.put("msg", "hello");

			JSONTransmitter transmitter = new JSONTransmitter();
			transmitter.execute(new JSONObject[] {toSend});

		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

Now I’ll just discuss the important lines which is wrapped in the try block. Observe toSend.put(“msg”, “hello”). looking back to our server code, “msg” is our critical data to be reversed. JSONTransmitter is our class that will be tackled below. Because it is a child of AsyncTask class, the way we execute a command is transmitter.execute(new JSONObject[] {toSend}). In our parameter, I passed an array of JSONObject which only contains 1 object, the toSend.

Let’s have this class that will send JSON object as String to PHP.

JAVA


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {

    String url = "http://10.0.2.2/coffeeCodes/";

    @Override
    protected JSONObject doInBackground(JSONObject... data) {
        JSONObject json = data[0];
		HttpClient client = new DefaultHttpClient();
		HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);

		JSONObject jsonResponse = null;
        HttpPost post = new HttpPost(url);
		try {
	        StringEntity se = new StringEntity("json="+json.toString());
	        post.addHeader("content-type", "application/x-www-form-urlencoded");
	        post.setEntity(se);

	        HttpResponse response;
			response = client.execute(post);
			String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());

			jsonResponse=new JSONObject(resFromServer);
			Log.i("Response from server", jsonResponse.getString("msg"));
		} catch (Exception e) {	e.printStackTrace();}

        return jsonResponse;
    }

}

On our class declaration of JSONTransmitter in line 1, we extended the AsyncTask class that passes 3 data types. AsyncTask is used for proper execution of Threads in Android. Inside our diamond operator , the first data type we declared is for the parameters’ type, then for progress and result respectively. In our case, we pass parameters to our JSONTransmitter object in JSONObject type. we broadcast update also in JSONObject, and we return the result in JSONObject.

String url = "http://10.0.2.2/coffeeCodes/";

Yes, it is what it looks like. http://10.0.2.2/coffeeCodes/ is where our server script will be hosted. well usually in web development we use “localhost” instead of 10.0.2.2 . But if we use localhost in this matter, localhost will be referring to your emulator’s system rather than your apache server (or what not). If you don’t have a clue on how we came up with “localhost” and how to put up your server codes, you would want to watch this first.

JSONObject json = data[0];

You might wonder about this first statement in our doInBackground method. The “data” variable is in JSONObject which is in array format. So what we did here is to take the first item in the array. Well that would be our scope of this program, only one JSONObject will be executed, just to make things simple.

HttpClient client = new DefaultHttpClient();

Think of “client” as Harry Potter’s Owl ;). it will be the one to send and execute data that we will build.

HttpPost post = new HttpPost(url);

“post” is our envelope. it carries our JSONObject and other necessary details such as to where we would send out message. In this case, we passed “url” (the class variable) as our send address.

StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);

And these are our contents. If you are familiar with HTTP headers, this won’t look like an alien to you. The handler of our json would be the StringEntity se. and if you noticed, we mutated our json to string form and as it would look like, it will be… json = {“msg” : “hello”}

So, let’s do the magic.

HttpResponse response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());

jsonResponse=new JSONObject(resFromServer);
Log.i("Response from server", jsonResponse.getString("msg"));

client.execute(post); The owl just flew and immediately came back and dropped the reply to your mailbox, “HttpResponse response”. Because we don’t speak Parrseltongue, we need a translator org.apache.http.util.EntityUtils.toString(response.getEntity()). Assuming that it is in JSON format, we then pass the response to our JSON parser JSONObject(resFromServer) and finally output our message to the LogCat.

Screenshot from 2013-10-20 12:21:39

Meet JSON !

Ever wondered about ways to connect users of your Android App through the internet with less difficulty in data manipulation? One way would be developing the application fully as a web app and view it on a WebView. But sometimes you may still want to have implementations using its native features. And JSON can help you with that. Well, not in the process of data streaming but in easy data manipulation.

JavaScript passing Post data to PHP via AJAX

$.post(url, 
       {action:"register", params:"params"}, 
       function(data) {
             console.log(data);
});

I have been using JSON objects to be passed through the ajax call like the above jQuery code, for quite some time and that’s it. One time I became so curious about this technology about why I see it everywhere. If JSON can be passed between JS and PHP, would it be possible if I use it within Android and send ’em to a PHP Server code? Then I visited JSON official site

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

– JSON.org

And I said to myself… “OOOOHHHHHH! this means big for my coding convention”. Immediately, ideas came passing through my mind of a lot of possibilities of my future projects. I now use JSON widely across all my projects in PHP, Android, and plainly Java and I want to share it with you.

This blog entry will not be focusing on the technical details of what JSON is or how its data structure was designed and how. Those details can be acquired by going to the official website. The purpose of this entry is to invite non JSON users to pretty much follow the trend.

Where is JSON used in today’s mainstream tech? It’s everywhere ! ! !

Not to mention, Youtube, flickr, Facebook, Google+, and the list goes on.

So What Are The Possibilities If I use JSON?

A lot, basically. One of it is that you could make a RESTful Web API. But because I Love Android, I would focus in Android realm.

In this one I would like to show an implementation using Android.

JAVA (CLIENT)


	HttpClient client = new DefaultHttpClient();
	HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);

        HttpPost post = new HttpPost("http://localhost/jsonTest"); 
                                      // or whatever url you have to your chosen folder
        
        HttpResponse httpResponse = client.execute(post);

        // catch whatever the server prints
        String response = org.apache.http.util.EntityUtils.toString(httpResponse.getEntity());
        
        // to be continued
     /* ... */

PHP (SERVER)

        $userInfo = array("first_name"=>"john", "last_name"=>"doe");
        echo json_encode($userInfo); // outputs as string

JAVA

Going back to our Java code, we can then instantiate a JSONObject for the caught JSON string

     /* ... */
     JSONObject resFromServer = new JSONObject(response);

     // AND THEN...
     Log.i("user first and last name", 
                       resFromServer.getString("first_name")
                       +" "+resFromServer.getString("last_name"));

We can now get any data within the object by calling the method .getString() for strings, .getInt() for Integer data type, getDouble, getBoolean, and more depending on what data type you want to retrieve.

But of course, these codes alone WILL NOT work. BUMMER.

Android would only allow you to call HTTP methods using an object that inherits AsyncTask. For a complete tutorial on how to send and retrieve JSON data from and to Android, read Sending JSON Data From Android to a PHP Script, which for now is still on draft.