Android访问php webservice
如果是PHP做的服务端,而我们要用android去访问,怎么办?当然可以用REST,但也可以用点笨的方法,比如可以让PHP的服务端返回JSON或XML数据,而Android端则可以用APACHE的httpclient去访问。
下面是一个例子,假设数据表中users表有如下字段(mysql):
idusers,UserName,FullName
加点数据,然后在服务端建立一个webservice1.php,作用是直接返回服务端数据库的数据,如下:
<?phpif (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);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端发送的数据保存到服务端了。
Android访问php webservice的更多相关文章
- 如何解析android访问webservice返回的SoapObject数据(可用)
怎么解析android访问webservice返回的SoapObject数据 本帖最后由 kkDragon123 于 2013-03-26 15:50:07 编辑 我的数据如下:mingdanResp ...
- (转)Android访问webservice
纠正网上乱传的android调用Webservice方法. 1.写作背景: 笔者想实现android调用webservice,可是网上全是不管对与错乱转载的文章,结果不但不能解决问题,只会让人心烦 ...
- android访问webservice
// nameSpace 命名空间,methodName:方法名字:maps:参数集合:webserviceUrl:访问的webservice的网址:比如:http://17.18.199.100:8 ...
- 在Android中调用WebService
某些情况下我们可能需要与Mysql或者Oracle数据库进行数据交互,有些朋友的第一反应就是直接在Android中加载驱动然后进行数据的增删改查.我个人不推荐这种做法,一是手机毕竟不是电脑,操作大量数 ...
- Android访问中央气象台的天气预报API得到天气数据
最新说明:该接口已失效! 2014-03-04 可申请它公布的API,需申请:http://smart.weather.com.cn/wzfw/smart/weatherapi.shtml 在用A ...
- Android访问WCF服务
原文链接:http://www.cnblogs.com/VinC/archive/2011/02/24/1964049.html 本章目的: 用Wcf建立可以上Android可以访问的数据服务, 数据 ...
- android之调用webservice 实现图片上传
转:http://www.cnblogs.com/top5/archive/2012/02/16/2354517.html public void testUpload(){ try{ String ...
- 在Android中使用Android Ksoap2调用WebService
一.WebService介绍 WebService是基于SOAP协议可实现web服务器与web服务器之间的通信,因采用SOAP协议传送XML数据具有平台无关性,也是成为解决异构平台之间通信的重要解决方 ...
- Android访问远程网页取回json数据
php代码 $array = array( 'username'=>'杨铸', 'password'=>'123456', 'user_id'=>);echo json_enc ...
随机推荐
- Colorful Lecture Note
Colorful Lecture Note 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 Little Hi is writing an algorithm lectu ...
- SQL Server 2008 Windows身份验证改为混合模式身份验证 及修改sa密码
由于需要,要把SQL2008单一的Windows身份验证改为混合模式身份验证.在此做一备忘. 步骤: 1.用Windows身份验证方式进入SQL2008,在[对象资源管理器]右键击[根目录]:
- 深入浅出JDBC-操作时间与大对象(Clob/Blob)
一.时间(Date.Time.Timestamp) java.sql.Date/java.sql.Time/java.sql.Timestamp extends java.util.Date publ ...
- Tomcat配置域名和虚拟文件夹
说明: 我在本机中添加域名模拟,假设是主机直接配置也能够使用.我用的tomcat是apache-tomcat-7.0.42 本地添加域名 本文介绍怎样通过改动tomcat的配置.实现通过IP地址或者域 ...
- 使用 pm2-web 监控 pm2 服务运行状态
pm2-web 是一款 pm2 服务状态监控程序,基于 web . 安装 $ npm install -g pm2-web 运行(默认是在8080端口) $ pm2-web 配置 pm2-web 将会 ...
- mysql concat函数进行模糊查询
concat() 函数,是用来连接字符串. 精确查询: select * from user where name=”zhangsan” 模糊查询: select * from user where ...
- OpenShift DNS的机制
为什么不直接用kube-dns? 为什么不直接用kube-dns? 为什么不直接用kube-dns? 感谢各位前辈的专研,在下午有限的时间里把Openshift DNS的机制理了一下.更详细的材料大家 ...
- Python学习(五)函数 —— 自定义函数
Python 自定义函数 函数能提高应用的模块性,和代码的重复利用率.Python提供了许多内建函数,比如print()等.也可以创建用户自定义函数. 函数定义 函数定义的简单规则: 函数代码块以de ...
- Python学习(九)IO 编程 —— 文件夹及文件操作
Python 文件夹及文件操作 我们经常会与文件和目录打交道,对于这些操作,python可以使用 os 及 shutill 模块,其中包含了很多操作文件和目录的函数. os 可以执行简单的文件夹及文件 ...
- JSONObject 转换 JSON复杂对象
Bean定义: public class GetM100DataResponse { private String service;//接口代码 private String sessionId;// ...