android访问php webservice简单一例
如果是PHP做的服务端,要用android去访问,如何办?当然可以用REST,但也可以用点
笨的方法,比如PHP的服务端可以用JSON和XML提供返回的数据,而android端则可以用
APACHE的httpclient去访问.
下面是一个例子,假设数据表中users表有如下字段(mysql):
idusers,UserName,FullName,加点数据.然后在服务端PHP,建立一个
webservice1.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();}