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

26 thoughts on “Sending JSON Data From Android to a PHP Script

      1. oh ok, sorry. let’s try to debug…
        are you using the exact codes from above post? if you are, maybe you may have to check your xampp server if it’s running.

        then do the codes below.

        jsonResponse=new JSONObject(resFromServer);
        comment this line, and replace it with…
        Log.i(resFromServer);

    1. Do you mean pass the variable from JSONTransmitter class to the MainActivity? if that’s the case, I sometimes use .get() method or assign values to a public static variable of a class ( which makes it somehow a global variable )

    1. let’s say you have this class…

      class Constants {
      public static String msg = “”;
      }

      then in your JSONTransmitter line 35:
      Constants.msg = jsonResponse.getString(“msg”);

      and somewhere in your MainActivity:

      if( ! Constants.msg.equals(“”) ) // if Constant.msg is NOT an empty String
      // do something with Constants.msg
      Log.i( “tag”, Constants.msg );

      Have you tried this method?

  1. Please, how to send a list? Example:

    JSONObject toSend = new JSONObject();
    toSend.put(“msg”, “nova”);
    toSend.put(“msg”, “teste”);
    toSend.put(“msg”, “asd”);
    toSend.put(“msg”, “tsafasd”);
    toSend.put(“msg”, “udfhjdfghdfg”);

    Here get only a position:

    JSONObject json = data[0];

    How to get all position to send object JSONObject json to server php?

    Sorry my english =/

    1. do you mean you want to send let’s say a user information?

      toSend.put(“first_name”, “nova”);
      toSend.put(“last_name”, “teste”);
      toSend.put(“phone_number”, “5162586”);

      ??

      if that’s the case, you can directly access it through the php code.

      1. Thank you for your help =)

        I would send a list of the same parameter.
        for example: The list of phone contacts.

        JSONObject Tosend = new JSONObject ();
        toSend.put (“contact”, “vinicius”);
        toSend.put (“number”, “888888888”);

        But I would send the entire list in one post and not send a contact at a time. It would be an array of contacts, understand?

  2. is just an example, I know I would not be so for each examente

    JSONObject Tosend = new JSONObject ();

    foreach(contactList as toSend){
    toSend.put (“contact”, “vinicius”);
    toSend.put (“number”, “888888888”);
    }

    understand what I am trying to do?

  3. would look like this?

    JSONObject jo = new JSONObject();

    jo.put(“firstName”, “vinicius”);
    jo.put(“lastName”, “8978978978978”);

    jo.put(“name”, “joao”);
    jo.put(“number”, “333333333”);

    jo.put(“name”, “maria”);
    jo.put(“number”, “444444444”);

    JSONArray ja = new JSONArray();
    ja.put(jo);

    JSONObject tosend = new JSONObject();
    tosend .put(“MyJson”, ja);

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

  4. thank you for your tutorial. i have tried this code but when i compile it i have an empty result i think i have a problem from server but i can’t solve it can you hep me??
    i’m waiting for your answer

      1. do you mean php code??i use the same code

        msg = strrev($data->msg);
        echo $data;
        // echo json_encode($data);

        }
        ?>

  5. hi dear
    i have a question about login. i want to send user and pass data to a php. but i do not know how?
    i can do it for one entry but i do not know how to do it for two parameters.
    Thanks in advanced.

Leave a comment