How to post JSON data from Android to PHP Codeigniter

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. This article explains how to client-server web service communication using Android and PHP, we will use JSON as the data.

We will build a simple calculator web service that has features such as add and multiply.

apikey represent key to access the webservice, the server will reject the request if the key is invalid, in this article we use “mykey123”
command represent what command request we want to use, in this article we use “add” or “multiply”
a and b represent input value we want to calculate

Java Code :

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://localhost/client/index.php/android");

        try {
            // Add your data

        	JSONObject json=new JSONObject();
        	json.put("apikey","mykey123");
        	json.put("command","add");
        	json.put("a","10");
        	json.put("b","20");

        	Log.d("JSON",json.toString());
            List nameValuePairs = new ArrayList(1);
            nameValuePairs.add(new BasicNameValuePair("json", json.toString()));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            String responseBody = EntityUtils.toString(response.getEntity());
            Log.d("JSON","RESPONSE : " + responseBody);

        } catch (ClientProtocolException e) {
        	Log.e("JSON",e.getMessage());
        } catch (IOException e) {
        	Log.e("JSON",e.getMessage());
        } catch (JSONException e) {
                Log.e("JSON",e.getMessage());
	}

CodeIgniter Code of Android.php Controller



input->post()==null){
				die;
			}

			$raw = $this->input->post();
			$this->data = json_decode($raw['json']);

			$this->apikey = $this->data->apikey;
			$this->command = $this->data->command;
			$this->a = $this->data->a;
			$this->b = $this->data->b;

			if($this->apikey=="mykey123"){

				switch($this->command){

					case "add":	
							$this->response = $this->a + $this->b;
					break;
                                        case "multiply":	
							$this->response = $this->a * $this->b;
					break;			
				}//end switch

				$arr = array("command"=>$this->command,
						"response"=>$this->response
				);

				echo json_encode($arr);
			}//end if
			else{
				echo "invalid request dear";
			}

	}//end of index function

}//end of class Android

The code above will send response formated JSON data as {"command":"add","response":"30"}

One thought on “How to post JSON data from Android to PHP Codeigniter”

Comments are closed.