Click here to Skip to main content
13,901,221 members
Click here to Skip to main content
Add your own
alternative version


105 bookmarked
Posted 11 Oct 2011
Licenced CPOL

Send and Receive JSON between Android and PHP Web Service

, 12 Oct 2011
Rate this:
Please Sign up or sign in to vote.
Set and get data via PHP Web Service between Android and PHP


You are creating an Android app and want to read data from a MySQL database and send data. We will create a Web Service in PHP, read from the MySQL database, and let the Android connect with the Web Service and send data, and the Web Service will save it and another Web Service will read data from MySQL and send it to the Android app.

Using the Code

First, we have to create the Web service to read data from the MySQL database.

<pre>/* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {
  /* soak in the passed variable or set our own */
  $number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
  $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
  $user_id = intval($_GET['user']); //no default
  /* connect to the db */
  $link = mysql_connect('localhost','root','123456') or die('Cannot connect to the DB');
  mysql_select_db('TEST',$link) or die('Cannot select the DB');
  /* grab the posts from the db */
  //$query = "SELECT post_title, guid FROM wp_posts WHERE post_author = 
  //  $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
  $query = "SELECT * FROM `test`.`users`;";
  $result = mysql_query($query,$link) or die('Errant query:  '.$query);
  /* create one master array of the records */
  $posts = array();
  if(mysql_num_rows($result)) {
    while($post = mysql_fetch_assoc($result)) {
      $posts[] = array('post'=>$post);
  /* output in necessary format */
  if($format == 'json') {
    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts));
  else {
    header('Content-type: text/xml');
    echo '';
    foreach($posts as $index => $post) {
      if(is_array($post)) {
        foreach($post as $key => $value) {
          echo '<',$key,'>';
          if(is_array($value)) {
            foreach($value as $tag => $val) {
              echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
          echo '</',$key,'>';
    echo '';
  /* disconnect from the db */

Here is the code for the Android activity to read from the Web Service and parse the JSON object:

public void clickbutton(View v) {
    try {

        // Log.i(getClass().getSimpleName(), "send  task - start");
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpParams p = new BasicHttpParams();
        // p.setParameter("name", pvo.getName());
        p.setParameter("user", "1");

        // Instantiate an HttpClient
        HttpClient httpclient = new DefaultHttpClient(p);
        String url = "" + 
        HttpPost httppost = new HttpPost(url);

        // Instantiate a GET HTTP method
        try {
            Log.i(getClass().getSimpleName(), "send  task - start");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
            nameValuePairs.add(new BasicNameValuePair("user", "1"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost,
            // Parse
            JSONObject json = new JSONObject(responseBody);
            JSONArray jArray = json.getJSONArray("posts");
            ArrayList<HashMap<String, String>> mylist = 
                   new ArrayList<HashMap<String, String>>();

            for (int i = 0; i < jArray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = jArray.getJSONObject(i);
                String s = e.getString("post");
                JSONObject jObject = new JSONObject(s);

                map.put("idusers", jObject.getString("idusers"));
                map.put("UserName", jObject.getString("UserName"));
                map.put("FullName", jObject.getString("FullName"));

            Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        // Log.i(getClass().getSimpleName(), "send  task - end");

    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),

Here is the PHP code to send data to the Web Service and save it:

//$json=$_GET ['json'];
$json = file_get_contents('php://input');
$obj = json_decode($json);
//echo $json;

$con = mysql_connect('localhost','root','123456') 
       or die('Cannot connect to the DB');
  /* grab the posts from the db */
  //$query = "SELECT post_title, guid FROM wp_posts WHERE 
  //  post_author = $user_id AND post_status = 'publish'
  // ORDER BY ID DESC LIMIT $number_of_posts";
mysql_query("INSERT INTO `test`.`users` (UserName, FullName)
VALUES ('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')");
  //$posts = array($json);
  $posts = array(1);
    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts)); 

Android activity to send data to the Web Service as a JSON object to save in the MySQL database:

public void clickbuttonRecieve(View v) {
    try {
        JSONObject json = new JSONObject();
        json.put("UserName", "test2");
        json.put("FullName", "1234567");
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpClient client = new DefaultHttpClient(httpParams);
        //String url = "" + 
        //             "json={\"UserName\":1,\"FullName\":2}";
        String url = "";

        HttpPost request = new HttpPost(url);
        request.setEntity(new ByteArrayEntity(json.toString().getBytes(
        request.setHeader("json", json.toString());
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        if (entity != null) {
            InputStream instream = entity.getContent();

            String result = RestClient.convertStreamToString(instream);
            Log.i("Read from server", result);
            Toast.makeText(this,  result,
    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),

Points of Interest

To connect to your emulator, you can use this link:

To read the JSON object in the Web Service, you can use this line of code:

$json = file_get_contents('php://input');
$obj = json_decode($json);


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Hamdy Ghanem
Software Developer (Senior)
Egypt Egypt
Hamdy Ghanem
Senior Software Engineer / System Architect
Experience: +11 years
Graduated from Munifia University, faculty of science, Math and computer science department May 1999

Experience Brief
11+ years of experience in software development field.
In these years I used most of common software developing tools of Microsoft, And with many nationalities and cultures.
I worked in large scale projects of client side, desktop, web application and mobile phones that involved integration with other system using different technologies I've been working using .NET technologies for 8 years.
Currently, I work as a senior software engineer for CogWin as well as a testing/QA consultant. We develop large scale applications for a high profile customer.
Beside developing and managing, I worked in the last year as a professional tester from developer point of view and applying software evaluation metrics on source code and reverse engineering.
I worked as a team leader more than four years
My experience involved using agile methodology using team foundation server
from 1year I am very interested in Android development
I have a published some applications in the Android Market

Strong skills troubleshooting and debugging production systems are essential
My key skills
High performance, hard worker and new technologies enthusiast
C#,, C++, Java ,php, Python , OOP SQL Server (2000, 2005, 2008),Oracle, Mysql , Java , SSRS ,Source safe, Ontology, Android, ASP.NET ,Ajax, • WPF,WCF, Entity Framework, LINQ, CFG , state machine , Ontology, Decision Tree , Cloud Systems, CRM ,JavaScript, XML, UML, Crystal report , LINQ, Silverlight

You may also be interested in...


Comments and Discussions

QuestionThis code don't insert row in my database Pin
tainstvennyy programmer14-Jan-17 3:40
membertainstvennyy programmer14-Jan-17 3:40 
QuestionI am using MIT APP inventor with mysql and php Pin
_______________________22-Sep-16 16:51
member_______________________22-Sep-16 16:51 
QuestionHow to receive data using webservice WordPress to Android application Pin
Member 1273910713-Sep-16 17:53
memberMember 1273910713-Sep-16 17:53 
QuestionShoot data in a TextView? Pin
Member 1197479220-Oct-15 3:20
memberMember 1197479220-Oct-15 3:20 
QuestionSend bulk data to web server. Pin
Member 1109450519-Sep-14 0:34
memberMember 1109450519-Sep-14 0:34 
QuestionAbout Editing Or Deleting Or Modifying Pin
Hercules4486-Aug-14 0:50
memberHercules4486-Aug-14 0:50 
GeneralMy vote of 3 Pin
xfzheng27-May-14 15:01
memberxfzheng27-May-14 15:01 
GeneralMy vote of 3 Pin
Member 1063458718-May-14 0:13
memberMember 1063458718-May-14 0:13 
BugDatabase detail Pin
creatorb7-Apr-14 4:16
membercreatorb7-Apr-14 4:16 
QuestionError converting result java.lang.nullpointerexception, error parsing data org.json.JSONEception. Pin
Cyber1226-Feb-14 21:06
memberCyber1226-Feb-14 21:06 
Questionhow to recive data using to andorid expandable listview Pin
beniv11-Nov-13 4:19
memberbeniv11-Nov-13 4:19 
AnswerRe: how to recive data using to andorid expandable listview Pin
creatorb7-Apr-14 4:12
membercreatorb7-Apr-14 4:12 
Questionthanksss Pin
Riza Savina28-Oct-13 21:09
memberRiza Savina28-Oct-13 21:09 
QuestionJSONException: Value Errant of type java.lang.String cannot be converted to JSONObject Pin
Member 1016646930-Jul-13 23:15
memberMember 1016646930-Jul-13 23:15 
AnswerRe: JSONException: Value Errant of type java.lang.String cannot be converted to JSONObject Pin
ravi koradiya1-Apr-14 23:34
memberravi koradiya1-Apr-14 23:34 
GeneralMy vote of 2 Pin
prajapati_rakesh24-Jul-13 2:33
memberprajapati_rakesh24-Jul-13 2:33 
QuestionHttpHostConnectException - connection to localhost refused. Pin
Member 1014185810-Jul-13 0:48
memberMember 1014185810-Jul-13 0:48 
Bugerror Pin
Member 101418589-Jul-13 23:31
memberMember 101418589-Jul-13 23:31 
Questionerroe Pin
Member 101418589-Jul-13 23:11
memberMember 101418589-Jul-13 23:11 
QuestionRequest for web service Pin
Rajivvaddi12-Jun-13 1:54
memberRajivvaddi12-Jun-13 1:54 
Questionsockettimeout exception Pin
Member 1001597329-Apr-13 2:22
memberMember 1001597329-Apr-13 2:22 
AnswerRe: sockettimeout exception Pin
Hamdy Ghanem29-Apr-13 2:29
memberHamdy Ghanem29-Apr-13 2:29 
GeneralRe: sockettimeout exception Pin
Member 1001597330-Apr-13 0:21
memberMember 1001597330-Apr-13 0:21 
QuestionKOUKOU Pin
Member 999966319-Apr-13 6:21
memberMember 999966319-Apr-13 6:21 
QuestionNo Error but no functionality :-/ Pin
Member 968670118-Mar-13 9:39
memberMember 968670118-Mar-13 9:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190306.1 | Last Updated 12 Oct 2011
Article Copyright 2011 by Hamdy Ghanem
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid