android访问php webservice简单一例(转)

晚上转的一篇,其实算不上什么webservice,搞了个类似接口返回一段xml或者json,是一种交互的方式,但始终觉得不是最好的。

如果是PHP做的服务端,要用android去访问,如何办?当然可以用REST,但也可以用点

笨的方法,比如PHP的服务端可以用JSON和XML提供返回的数据,而android端则可以用

APACHE的httpclient去访问.

  下面是一个例子,假设数据表中users表有如下字段(mysql):

idusers,UserName,FullName,加点数据.然后在服务端PHP,建立一个

webservice1.php,作用是直接返回服务端数据库的数据,如下:

Java代码  收藏代码
  1. <?php   
  2. if(isset($_GET['user']) && intval($_GET['user'])) {  
  3.   
  4.   
  5.      $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default  
  6.   $user_id = intval($_GET['user']); //no default  
  7.   
  8.   /* 连接数据库*/  
  9.   $link = mysql_connect('localhost','root','xxxxx') or die('Cannot connect to the DB');  
  10.   mysql_select_db('jsonandroid',$link) or die('Cannot select the DB');  
  11.   
  12.      $query = "SELECT * FROM `users`;";  
  13.   $result = mysql_query($query,$link) or die('Errant query:  '.$query);  
  14.   
  15.     $posts = array();  
  16.   if(mysql_num_rows($result)) {  
  17.     while($post = mysql_fetch_assoc($result)) {  
  18.       $posts[] = array('post'=>$post);  
  19.     }  
  20.   }  
  21.   
  22.   /* json格式*/  
  23.   if($format == 'json') {  
  24.     header('Content-type: application/json');  
  25.     echo json_encode(array('posts'=>$posts));  
  26.   }  
  27.   else {  
  28.     header('Content-type: text/xml');  
  29.     echo '<posts>';  
  30.     foreach($posts as $index => $post) {  
  31.       if(is_array($post)) {  
  32.         foreach($post as $key => $value) {  
  33.           echo '<',$key,'>';  
  34.           if(is_array($value)) {  
  35.             foreach($value as $tag => $val) {  
  36.               echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';  
  37.             }  
  38.           }  
  39.           echo '</',$key,'>';  
  40.         }  
  41.       }  
  42.     }  
  43.     echo '</posts>';  
  44.   }  
  45.   
  46.   }  
  47.  ?>   

 

 

   则可以把数据表输出为JSON或者XML格式了.客户端的ANDROID调用:

Java代码  收藏代码
  1. try {  
  2.               
  3.             HttpParams httpParams = new BasicHttpParams();  
  4.             HttpConnectionParams.setConnectionTimeout(httpParams,  
  5.                     TIMEOUT_MILLISEC);  
  6.             HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);  
  7.               
  8.             HttpParams p = new BasicHttpParams();  
  9.               
  10.             p.setParameter("user", "1");  
  11.   
  12.               
  13.             HttpClient httpclient = new DefaultHttpClient(p);  
  14.             String url = "http://10.0.2.2:8082/myphp/phpWebservice/webservice1.php?user=1&format=json";  
  15.             HttpPost httppost = new HttpPost(url);  
  16.   
  17.               
  18.             try {  
  19.                 Log.i(getClass().getSimpleName(), "send  task - start");  
  20.                   
  21.                 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(  
  22.                         2);  
  23.                 nameValuePairs.add(new BasicNameValuePair("user", "1"));  
  24.                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
  25.                 ResponseHandler<String> responseHandler = new BasicResponseHandler();  
  26.                 String responseBody = httpclient.execute(httppost,  
  27.                         responseHandler);  
  28.                 // 解析JSON返回的                JSONObject json = new JSONObject(responseBody);  
  29.                 JSONArray jArray = json.getJSONArray("posts");  
  30.                 ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();  
  31.   
  32.                 for (int i = 0; i < jArray.length(); i++) {  
  33.                     HashMap<String, String> map = new HashMap<String, String>();  
  34.                     JSONObject e = jArray.getJSONObject(i);  
  35.                     String s = e.getString("post");  
  36.                     JSONObject jObject = new JSONObject(s);  
  37.   
  38.                     map.put("idusers", jObject.getString("idusers"));  
  39.                     map.put("UserName", jObject.getString("UserName"));  
  40.                     map.put("FullName", jObject.getString("FullName"));  
  41.   
  42.                     mylist.add(map);  
  43.                 }  
  44.                 Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();  

 

 

  再搞个webservice2.php,该文件用来把客户端传送过去的JSON数据保存

Java代码  收藏代码
  1. <?php   
  2.   
  3. $json = file_get_contents('php://input');  
  4. $obj = json_decode($json);  
  5.   
  6. //echo $json;  
  7.   
  8.   
  9. //保存数据库  
  10. $con = mysql_connect('localhost','root','XXX') or die('Cannot connect to the DB');  
  11. mysql_select_db('jsonandroid',$con);  
  12.   
  13.   mysql_query("INSERT INTO `users` (UserName, FullName)  
  14. VALUES ('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')");  
  15.   
  16. mysql_close($con);  
  17.   $posts = array(1);  
  18.     header('Content-type: application/json');  
  19.     echo json_encode(array('posts'=>$posts));  
  20.   
  21. ?>  

 

 

  而ANDROID端的,可以构造JSON,发送到webservice2.php

 

Java代码  收藏代码
  1. try {  
  2.             JSONObject json = new JSONObject();  
  3.             json.put("UserName", "test2");  
  4.             json.put("FullName", "1234567");  
  5.             HttpParams httpParams = new BasicHttpParams();  
  6.             HttpConnectionParams.setConnectionTimeout(httpParams,  
  7.                     TIMEOUT_MILLISEC);  
  8.             HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);  
  9.             HttpClient client = new DefaultHttpClient(httpParams);  
  10.                                     String url = "http://10.0.2.2:8082//myphp/phpWebservice/webservice2.php";  
  11.   
  12.             HttpPost request = new HttpPost(url);  
  13.             request.setEntity(new ByteArrayEntity(json.toString().getBytes(  
  14.                     "UTF8")));  
  15.             request.setHeader("json", json.toString());  
  16.             HttpResponse response = client.execute(request);  
  17.             HttpEntity entity = response.getEntity();  
  18.               
  19.             if (entity != null) {  
  20.                 InputStream instream = entity.getContent();  
  21.   
  22.                 String result = RestClient.convertStreamToString(instream);  
  23.                 Log.i("Read from server", result);  
  24.                 Toast.makeText(this,  result,  
  25.                         Toast.LENGTH_LONG).show();  
  26.             }  

 

 

   这样,就可以把ANDROID发送的数据保存到服务端了

 
 
 
 
 
posted @ 2013-03-21 22:50  不再犹豫、  阅读(312)  评论(0编辑  收藏  举报