Click here to Skip to main content
Click here to Skip to main content

Send and Receive JSON between Android and PHP Web Service

By , 12 Oct 2011
 

Introduction

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.

<?php  
<pre>/* require the user as the parameter */
<pre>//http://localhost:8080/sample1/webservice1.php?user=1
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 */
  @mysql_close($link);
}
?>

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 {
        // http://androidarabia.net/quran4android/phpserver/connecttoserver.php

        // Log.i(getClass().getSimpleName(), "send  task - start");
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                TIMEOUT_MILLISEC);
        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 = "http://10.0.2.2:8080/sample1/" + 
                     "webservice1.php?user=1&format=json";
        HttpPost httppost = new HttpPost(url);

        // Instantiate a GET HTTP method
        try {
            Log.i(getClass().getSimpleName(), "send  task - start");
            //
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    2);
            nameValuePairs.add(new BasicNameValuePair("user", "1"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost,
                    responseHandler);
            // 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"));

                mylist.add(map);
            }
            Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();

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

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

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

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

//Save
$con = mysql_connect('localhost','root','123456') 
       or die('Cannot connect to the DB');
mysql_select_db('TEST',$con);
  /* 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'}."')");
mysql_close($con);
//
  //$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.setConnectionTimeout(httpParams,
                TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpClient client = new DefaultHttpClient(httpParams);
        //
        //String url = "http://10.0.2.2:8080/sample1/webservice2.php?" + 
        //             "json={\"UserName\":1,\"FullName\":2}";
        String url = "http://10.0.2.2:8080/sample1/webservice2.php";

        HttpPost request = new HttpPost(url);
        request.setEntity(new ByteArrayEntity(json.toString().getBytes(
                "UTF8")));
        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,
                    Toast.LENGTH_LONG).show();
        }
    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
    }
}

Points of Interest

To connect to your emulator, you can use this link: http://10.0.2.2:8080/

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);

License

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
Member
Hamdy Ghanem
Senior Software Engineer / System Architect
Experience: +11 years
http://www.linkedin.com/in/hamdyghanem
hamdy.ghanem@gmail.com
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
Specialties
C#,VB.net, 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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionsockettimeout exceptionmemberMember 1001597329 Apr '13 - 2:22 
I receive sockettimeout exception. What must I do ? please help
AnswerRe: sockettimeout exceptionmemberHamdy Ghanem29 Apr '13 - 2:29 
check the port or the firewall !!
see this link
http://stackoverflow.com/questions/14641835/sockettimeoutexception-android[^]
GeneralRe: sockettimeout exceptionmemberMember 1001597330 Apr '13 - 0:21 
How must i do firewall settings ?
QuestionKOUKOUmemberMember 999966319 Apr '13 - 6:21 
DATA BASE PLEASE
QuestionNo Error but no functionality :-/memberMember 968670118 Mar '13 - 9:39 
Hey!
 
I have to use this code for an android application.
(with eclipse)
 
at this row I have problems:
 
responseBody = httpclient.execute(httppost, responseHandler);
 
If I write:
 
Toast.makeText(this, "this shows", Toast.LENGTH_LONG).show();
responseBody = httpclient.execute(httppost, responseHandler);
Toast.makeText(this, "this not", Toast.LENGTH_LONG).show();
 
can you help me?
AnswerRe: No Error but no functionality :-/memberHamdy Ghanem29 Apr '13 - 2:30 
check you webservice from a win browser
QuestionHttpHostConnectException - connection to localhost refusedmemberNataliewater5 Mar '13 - 20:16 
Thank you very much for your tutorial, it's really helpful!
 
Btw, I got some problems and hope you could give me guidance.
 
1) When I pressed on "Receive" Button, a toast text pop up and said that request failed - HttpHostConnectException - connection to localhost refused.
 
2) The "Send" Button has no response.
 
Thanks.
GeneralMy vote of 3memberPaul Conrad31 Dec '12 - 9:20 
More screen shots and a bit more detail would be helpful.
GeneralRESPECTmemberahmed_red23 Nov '12 - 2:51 
This was the Best and To the point description available all over internet for JSON sending and receiving on web end via android. HATS OFF!!
GeneralRe: RESPECTmemberjo le serb9 May '13 - 11:37 
All is said.
QuestionUnproper use of setEntity and setHeadermemberIlian Nikolov10 Nov '12 - 14:23 
This tutorial is very useful, however I spotted something ambiguous:
 
request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
request.setHeader("json", json.toString());
 
You are practically passing the content of the json through the header and not the entity. If you remove your setEntity line, this method is still going to work, although it doesn't seem like a good practice to do it this way.
GeneralMy vote of 4memberFawwad Ali Khan8 Aug '12 - 20:51 
Hi Hamdy Ghanem,
 
It is very good article.
Thanks
soft Developer india
QuestionDatabase detailsmembermbs98931 Jul '12 - 21:51 
Please tell me the databases and tables required in the web end
bilal

Questionplz rly me fastmemberyethendranaidu6 Jul '12 - 23:11 
I am completely new to the web services.i have lot of doudts i will be glad if u kindly reply to this message.I downloaded the project and imported that into my ecllipse.should i need to create a dynamic web project for this or is it ok if i just import this like the same.I am using a Jam server in the different computer and accessing the project.should i need to have both the projects in the same computer.the computers are connected in LAN.I have no errors in cone but i got a error on the project with an exlamatory mark.So please tell me what to do.
QuestionMissing filememberI Yeu1 Jul '12 - 8:30 
Hi,
 
I got this error seems like is lacking 3 jar files
 
Description Resource    Path    Location    Type
Project 'TestProo' is missing required library: 'D:\Hamdy\Working Folder\android-sdk-windows\google-gson-1.7.1\gson-1.7.1-javadoc.jar'  TestProo        Build path  Build Path Problem
Project 'TestProo' is missing required library: 'D:\Hamdy\Working Folder\android-sdk-windows\google-gson-1.7.1\gson-1.7.1-sources.jar'  TestProo        Build path  Build Path Problem
 
Project 'TestProo' is missing required library: 'D:\Hamdy\Working Folder\android-sdk-windows\google-gson-1.7.1\gson-1.7.1.jar' TestProo Build path Build Path Problem
 

Can you guide me? Thanks
AnswerRe: Missing filememberSzymon Woźniak11 Jul '12 - 2:14 
Just download Google GSON jar and import files into project (from project properties)
Questioncertain errors i am facingmemberMember 875988227 Mar '12 - 22:36 
i am getting 2 errors
1st - when the app starts it shows native typeface not found
2nd - when i click on receive button i get java.net.SocketException Permission Denied
Please help asap!
AnswerRe: certain errors i am facingmemberHamdy Ghanem27 Mar '12 - 22:41 
Hi
I think that u r missing a permission
are you trying to run this from localhost or from server side?
check this link
http://stackoverflow.com/questions/4253233/exception-with-web-service-java-net-socketexception-permission-denied-in-and[^]
GeneralRe: certain errors i am facingmemberMember 875988227 Mar '12 - 23:04 
ok now i am getting a new error
connection to http://localhost is refused
if i give any other address like 10.0.2.2 that is also getting refused!
GeneralRe: certain errors i am facingmemberHamdy Ghanem27 Mar '12 - 23:33 
Please check ur firewall
GeneralRe: certain errors i am facingmemberMember 875988227 Mar '12 - 23:38 
my firewall for all options is OFF
GeneralRe: certain errors i am facingmemberMember 875988228 Mar '12 - 19:38 
OK finally the code worked.. im getting this error when i want to receive data
Request Failed org.json.JSONException
Value <br of type java.lang.String cannot be converted to JSONObject
GeneralRe: certain errors i am facingmemberHamdy Ghanem28 Mar '12 - 20:05 
The exception should has details or message , any way the most exception is value of the json is could not parse will , so try to print json value and check the value
GeneralRe: certain errors i am facingmembersangisuke20 Apr '12 - 16:57 
im encounter the same problem to. turn out the json return a null value. why?
GeneralRe: certain errors i am facingmembersangisuke20 Apr '12 - 16:58 
i mean the "
 <br of type java.lang.String cannot be converted to JSONObject 
" error

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

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