Android访问php webservice简单一例


如果是PHP做的服务端,要用Android去访问,如何办?当然可以用REST,但也可以用点笨的方法,比如PHP的服务端可以用JSON和XML提供返回的数据,而android端则可以用APACHE的httpclient去访问.

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

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

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

  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调用:

  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();  
  • 1
  • 2
  • 下一页

相关内容