1、. 如果是 PHP 做的服务端,而我们要用android去访问,怎么办?当然可以用REST ,但也 可以用点笨的方法,比如可以让PHP 的服务端返回JSON 或 XML 数据,而 Android端则 可以用 APACHE 的 httpclient去访问。 下面是一个例子,假设数据表中users表有如下字段 (mysql): idusers,UserName,FullName 加点数据,然后在服务端建立一个webservice1.php,作用是直接返回服务端数据库的数 据,如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
2、 23 24 25 26 27 28 29 30 31 $post); /* json格式 */ if($format= json) header(Content-type: application/json); echo json_encode(array(posts=$posts); else header(Content-type: text/xml); echo ; foreach ($posts as $index = $post) if(is_array($post) foreach($postas $key = $value) echo ; if(is_array($value)
3、 foreach($valueas $tag = $val) 32 33 34 35 36 37 38 39 40 41 42 43 44 45 echo ,htmlentities($val),; echo ; echo ; ? 则可以把数据表输出为JSON 或者 XML 格式了,客户端的Android调用: ? 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 try HttpParams httpParams = newBasicHttpParams(); HttpConnectionParams.setConnectionTimeo
4、ut(httpParams, TIMEOUT_MILLISEC); HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC); HttpParams p = newBasicHttpParams(); p.setParameter(user, 1); HttpClient httpclient = newDefaultHttpClient(p); String url = http:/10.0.2.2:8082/myphp/phpWebservice/webservice1.php?user=1 HttpPost httpp
5、ost = newHttpPost(url); try Log.i(getClass().getSimpleName(), send task - start); List nameValuePairs = newArrayList(2); nameValuePairs.add(new BasicNameValuePair(user, 1); httppost.setEntity(newUrlEncodedFormEntity(nameValuePairs); ResponseHandler responseHandler = newBasicResponseHandler(); String
6、 responseBody = httpclient.execute(httppost, responseHandler); / 解析 JSON 返回的 JSONObject json = new JSONObject(responseBody); JSONArray jArray = json.getJSONArray(posts); ArrayList mylist = new ArrayList(); for (inti = 0; i FullName.); mysql_close($con); $posts = array(1); header(Content-type: applic
7、ation/json); echo json_encode(array(posts=$posts); ? 而 Android客户端,可以构造JSON ,发送到webservice2.php ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 try JSONObject json = newJSONObject(); json.put(UserName, test2); json.put(FullName, 1234567); HttpParams httpParams = newBasicHttpParams(); HttpConnect
8、ionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC); HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC); HttpClient client = newDefaultHttpClient(httpParams); String url = http:/10.0.2.2:8082/myphp/phpWebservice/webservice2.php; HttpPost request = newHttpPost(url); request.setEntity(new ByteArrayEntity(json.toString().getBytes(UTF8); request.setHeader(json, json.toString(); HttpResponse respo