Android訪問php webservice

來源:互聯網
上載者:User

如果是PHP做的服務端,而我們要用android去訪問,怎麼辦?當然可以用REST,但也可以用點笨的方法,比如可以讓PHP的服務端返回JSON或XML資料,而Android端則可以用APACHE的httpclient去訪問。

下面是一個例子,假設資料表中users表有如下欄位(mysql):
idusers,UserName,FullName

加點資料,然後在服務端建立一個webservice1.php,作用是直接返回服務端資料庫的資料,如下:

<?php if  (isset( $_GET [ 'user' ]) &&  intval ( $_GET [ 'user' ])) { $format  strtolower ( $_GET [ 'format' ]) ==  'json'  'json'  'xml' //xml is the default $user_id  intval ( $_GET [ 'user' ]);  //no default  /* 串連資料庫 */ $link  = mysql_connect( 'localhost' , 'root' , 'xxxxx' or  die ( 'Cannot connect to the DB' ); mysql_select_db( 'jsonandroid' , $link or  die ( 'Cannot select the DB' );  $query  "SELECT * FROM 'users'" ; $result  = mysql_query( $query , $link );  $posts  array (); if  (mysql_num_rows( $result )) { while ( $post  = mysql_fetch_assoc( $result )) { $posts [] =  array ( 'post' => $post ); } }  /* json格式 */ if ( $format  ==  'json' ) { header( 'Content-type: application/json' ); echo  json_encode( array ( 'posts' => $posts )); } else  { header( 'Content-type: text/xml' ); echo  '<posts>' ; foreach  ( $posts  as  $index  =>  $post ) { if  ( is_array ( $post )) { foreach ( $post  as  $key  =>  $value ) { echo  '<' , $key , '>' ; if  ( is_array ( $value )) { foreach ( $value  as  $tag  =>  $val ) { echo  '<' , $tag , '>' ,htmlentities( $val ), '</' , $tag , '>' ; } } echo  '</' , $key , '>' ; } } } echo  '</posts>' ; } } ?>

則可以把資料表輸出為JSON或者XML格式了,用戶端的Android調用:

try  { HttpParams httpParams =  new  BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC); HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);  HttpParams p =  new  BasicHttpParams();  p.setParameter( "user" "1" );  HttpClient httpclient =  new  DefaultHttpClient(p); String url =  "http://10.0.2.2:8082/myphp/phpWebservice/webservice1.php?user=1&format=json" ; HttpPost httppost =  new  HttpPost(url);  try  { Log.i(getClass().getSimpleName(),  "send task - start" );  List<NameValuePair> nameValuePairs =  new  ArrayList<NameValuePair>( 2 ); nameValuePairs.add( new  BasicNameValuePair( "user" "1" )); httppost.setEntity( new  UrlEncodedFormEntity(nameValuePairs)); ResponseHandler<String> responseHandler =  new  BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); // 解析JSON返回的 JSONObject json = new JSONObject(responseBody); JSONArray jArray = json.getJSONArray( "posts" ); ArrayList<HashMap<String, String>> mylist =  new  ArrayList<HashMap<String, String>>();  for  ( int  i =  0 ; i < jArray.length(); i++) { HashMap<String, String> map =  new  HashMap<String, String>(); JSONObject e = jArray.getJSONObject(i); String s = e.getString( "post" ); JSONObject jObject =  new  JSONObject(s);  map.put( "idusers" , jObject.getString( "idusers" )); map.put( "UserName" , jObject.getString( "UserName" )); map.put( "FullName" , jObject.getString( "FullName" ));  mylist.add(map); } Toast.makeText( this , responseBody, Toast.LENGTH_LONG).show();

再搞個webservice2.php,該檔案用來接受並儲存用戶端傳送過來的JSON資料。

<?php $json  file_get_contents ( 'php://input' ); $obj  = json_decode( $json );  //儲存資料庫 $con  = mysql_connect( 'localhost' , 'root' , 'XXX' or  die ( 'Cannot connect to the DB' ); mysql_select_db( 'jsonandroid' $con );  mysql_query( "INSERT INTO 'users' (UserName, FullName) VALUES ('" . $obj ->{'UserName '}."' '".$obj->{' FullName '}."' )");  mysql_close( $con );  $posts  array (1); header( 'Content-type: application/json' ); echo  json_encode( array ( 'posts' => $posts )); ?>

而Android用戶端,可以構造JSON,發送到webservice2.php

try  { JSONObject json =  new  JSONObject(); json.put( "UserName" "test2" ); json.put( "FullName" "1234567" ); HttpParams httpParams =  new  BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC); HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC); HttpClient client =  new  DefaultHttpClient(httpParams); String url =  "http://10.0.2.2:8082//myphp/phpWebservice/webservice2.php" ;  HttpPost request =  new  HttpPost(url); request.setEntity( new  ByteArrayEntity(json.toString().getBytes( "UTF8" ))); request.setHeader( "json" , json.toString()); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity();  if  (entity !=  null ) { InputStream instream = entity.getContent();  String result = RestClient.convertStreamToString(instream); Log.i( "Read from server" , result); Toast.makeText( this , result, Toast.LENGTH_LONG).show(); }

這樣就可以把Android端發送的資料儲存到服務端了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.