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 ...
随机推荐
- HAproxy + keepalived 实现双机热备
一.HAProxy简介: HAProxy提供高可用性.负载均衡以及基于TCP和HTTP应用的代理,支持虚拟主机,它是免费.快速并且可靠的一种解决方案.HAProxy特别适用于那些负载特大的web站点, ...
- 进程上下文VS中断上下文
转载:http://www.cnblogs.com/zzx1045917067/archive/2012/12/19/2824552.html 内核空间和用户空间是现代操作系统的两种工作模式,内核模块 ...
- 从Log4j迁移到LogBack的理由
英文原文:Reasons to prefer logback over log4j 无论从设计上还是实现上,Logback相对log4j而言有了相对多的改进.不过尽管难以一一细数,这里还是列举部分理由 ...
- Setup SS5 Socks Proxy
Install and configure ss5 socks proxy with simple authentication SS5 is a high performance socks pro ...
- .NET:CLR via C# The CLR’s Execution Model
The CLR’s Execution Model The core features of the CLR memory management. assembly loading. security ...
- .NET:为什么不能在子类或外部发布C#事件
背景 一个朋友问了一个问题:“为什么不能在子类或外部发布C#事件?”,我说我不知道,要看看生产的IL代码,下面我们看看. 测试 代码 using System; using System.Collec ...
- opencv CxImage 互转 (Mat)
//to Mat CxImage img; img.Load("C:\\f.jpg"); uint8_t* buf=NULL; int32_t len=0; bool rs =im ...
- Python学习 —— 阶段综合练习三
Python学习 —— 阶段综合练习三 综合之前文件与文件夹操作的学习,做以下实例练习:(建议先不要看代码,自己先试着写:代码仅供参考,有多种实现方法) 1. 目录文件遍历(二层目录结构) 1). ...
- iOS: 沙盒的详解和目录的获取
沙盒的详解: •iOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被称为沙盒 •iOS常用目录: –Bundle //该目录下的文件是用来存储应用程序包的 ...
- swfupload js中 file 对象的属性
name=3cc68cfc60b87e6dd6887d8a.jpg modificationdate=Wed Apr 21 15:48:30 UTC+0800 2010 filestatus=-1 ...