android访问php webservice简单一例

来源:互联网 发布:淘宝优惠券关键词 编辑:程序博客网 时间:2024/06/10 15:15
    博客分类:
  • Android
jsonhttpclientandroid 
  如果是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.   
  2. try {   
  3.                
  4.             HttpParams httpParams = new BasicHttpParams();   
  5.             HttpConnectionParams.setConnectionTimeout(httpParams,   
  6.                     TIMEOUT_MILLISEC);   
  7.             HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);   
  8.                
  9.             HttpParams p = new BasicHttpParams();   
  10.                
  11.             p.setParameter("user""1");   
  12.   
  13.                
  14.             HttpClient httpclient = new DefaultHttpClient(p);   
  15.             String url = "http://10.0.2.2:8082/myphp/phpWebservice/webservice1.php?user=1&format=json";   
  16.             HttpPost httppost = new HttpPost(url);   
  17.   
  18.                
  19.             try {   
  20.                 Log.i(getClass().getSimpleName(), "send  task - start");   
  21.                    
  22.                 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(   
  23.                         2);   
  24.                 nameValuePairs.add(new BasicNameValuePair("user""1"));   
  25.                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));   
  26.                 ResponseHandler<String> responseHandler = new BasicResponseHandler();   
  27.                 String responseBody = httpclient.execute(httppost,   
  28.                         responseHandler);   
  29.                 // 解析JSON返回的                JSONObject json = new JSONObject(responseBody);  
  30.                 JSONArray jArray = json.getJSONArray("posts");   
  31.                 ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();   
  32.   
  33.                 for (int i = 0; i < jArray.length(); i++) {   
  34.                     HashMap<String, String> map = new HashMap<String, String>();   
  35.                     JSONObject e = jArray.getJSONObject(i);   
  36.                     String s = e.getString("post");   
  37.                     JSONObject jObject = new JSONObject(s);   
  38.   
  39.                     map.put("idusers", jObject.getString("idusers"));   
  40.                     map.put("UserName", jObject.getString("UserName"));   
  41.                     map.put("FullName", jObject.getString("FullName"));   
  42.   
  43.                     mylist.add(map);   
  44.                 }   
  45.                 Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();  


  再搞个webservice2.php,该文件用来把客户端传送过去的JSON数据保存
Java代码 复制代码 收藏代码
  1.   
  2. <?php    
  3.   
  4. $json = file_get_contents('php://input');   
  5. $obj = json_decode($json);   
  6.   
  7. //echo $json;   
  8.   
  9.   
  10. //保存数据库   
  11. $con = mysql_connect('localhost','root','XXX') or die('Cannot connect to the DB');   
  12. mysql_select_db('jsonandroid',$con);   
  13.   
  14.   mysql_query("INSERT INTO `users` (UserName, FullName)   
  15. VALUES ('".$obj->{'UserName'}."''".$obj->{'FullName'}."')");   
  16.   
  17. mysql_close($con);   
  18.   $posts = array(1);   
  19.     header('Content-type: application/json');   
  20.     echo json_encode(array('posts'=>$posts));   
  21.   
  22. ?>  


  而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发送的数据保存到服务端了