Wednesday, 5 September 2012

Android - PHP server connectivity

In android php server connectivity is very easy task. Here I am giving android code which will communicate with php script on wamp server. At first let's have a look at android client code.

1. Android Client:
At first you have to create array list with name value pair. Here is code for that,

Code:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name1", "value1"));
nameValuePairs.add(new BasicNameValuePair("name2", "value2"));

In this way you can put any number of name value pairs. You can access these values at server side means in php script in $_REQUEST array by there name. Means "value1" can be accessed using $_REQUEST['name1'].
Now we can send this array list to server as given below.

Code:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ip_address_of_server/test.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is1 = entity.getContent();
byte[]b = new byte[200];
is1.read(b);
String responce= new String(b);

In response you will get return value from server. If your response from server is in JSON format then you can parse that as given below,

Code:

JSONObject jo=new JSONObject(responce);
String res = jo.get("result");

Where "result" is name that you are returning from server.

2. Server Part:
At server you have to write php script. Here is sample code,

Code:
test.php

<?php
$done = array('result' => 'success', 'value1' => $_REQUEST['name1']);
echo json_encode($done);
?>

This script will return value related with "name1".

At android client in "result" you will get "success" message and in "value1" you will get respected value.



No comments:

Post a Comment