Android开发系列之调用WebService
我在学习Android开发过程中遇到的第一个疑问就是Android客户端是怎么跟服务器数据库进行交互的呢?这个问题是我当初初次接触Android时所困扰我的一个很大的问题,直到几年前的一天,我突然想到WebService是否可以呢?让WebService充当服务器端的角色,完成与服务器数据库操作相关的事情,而Android客户端只要按照WebService方法参数的要求去调用就行了。在当时我对这个解决方案的实现还没模糊,我想这个问题也是初学Android的朋友肯定会想到的问题。那么现在就让我们动手去实现它吧。
这个程序我们演示如何请求Web Service来获取服务端提供的数据。
由于我对C#比较熟悉,所以我优先使用自己熟悉的技术来搭建WebService的项目。很简单我们就用VS工具创建一个Web服务应用程序(VS2008,而从VS2010开始优先使用WCF来创建服务应用程序了,不过用WCF框架创建WebService也是很容易的)。
- [WebMethod]
- public string DataTableTest()
- {
- DataTable dt = new DataTable("userTable");
- dt.Columns.Add("id",typeof(int));
- dt.Columns.Add("name", typeof(string));
- dt.Columns.Add("email", typeof(string));
- dt.Rows.Add(1, "gary.gu", "guwei4037@sina.com");
- dt.Rows.Add(2, "jinyingying", "345822155@qq.com");
- dt.Rows.Add(3, "jinyingying", "345822155@qq.com");
- dt.Rows.Add(4, "jinyingying", "345822155@qq.com");
- return Util.CreateJsonParameters(dt);
- }
这个WebService的方法很简单,就是组建一个DataTable的数据类型,并通过CreateJsonParameters方法转化为JSON字符串。这里面的DataTable可以修改成从数据库端读取数据到DataTable对象。
- public static string CreateJsonParameters(DataTable dt)
- {
- StringBuilder JsonString = new StringBuilder();
- if (dt != null && dt.Rows.Count > 0)
- {
- JsonString.Append("{ ");
- JsonString.Append("\"Result_List\":[ ");
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- JsonString.Append("{ ");
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- if (j < dt.Columns.Count - 1)
- {
- JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
- }
- else if (j == dt.Columns.Count - 1)
- {
- JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
- }
- }
- if (i == dt.Rows.Count - 1)
- {
- JsonString.Append("} ");
- }
- else
- {
- JsonString.Append("}, ");
- }
- }
- JsonString.Append("]}");
- return JsonString.ToString();
- }
- else
- {
- return null;
- }
- }
这个方法是我从网上随便找到的一个方法,比较土了,就是直接拼接JSON字符串(无所谓,这不是我们要关心的重点)。
WebService端准备好,就可以将其发布到IIS。发布方法跟网站一样,如果是本机的话,可以直接测试WebService方法返回得到的结果,比如调用后会得到如下结果:
这里肯定有人问,这外面是XML,里面又是JSON,这不是“四不像”吗?是的,我这样做是想说明一点,WebService是基于Soap的,数据传输的格式就是XML,所以这里得到XML文档是理所当然。如果你想得到纯净的JSON字符串,可以使用C#中的WCF框架(可以指定客户端返回JSON格式)或者Java中的Servlet(直接刷出JSON文本)。
好,接下来我们要做两件事:
1、请求这个WebService得到这个JSON字符串
2、格式化这个JSON字符串在Android中显示
我们先提供一个助手类,这是我自己动手封装了一下这两个操作所需要的方法。
- /**
- * @author gary.gu 助手类
- */
- public final class Util {
- /**
- * @param nameSpace WS的命名空间
- * @param methodName WS的方法名
- * @param wsdl WS的wsdl的完整路径名
- * @param params WS的方法所需要的参数
- * @return SoapObject对象
- */
- public static SoapObject callWS(String nameSpace, String methodName,
- String wsdl, Map<String, Object> params) {
- final String SOAP_ACTION = nameSpace + methodName;
- SoapObject soapObject = new SoapObject(nameSpace, methodName);
- if ((params != null) && (!params.isEmpty())) {
- Iterator<Entry<String, Object>> it = params.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry<String, Object> e = (Map.Entry<String, Object>) it
- .next();
- soapObject.addProperty(e.getKey(), e.getValue());
- }
- }
- SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
- SoapEnvelope.VER11);
- envelope.bodyOut = soapObject;
- // 兼容.NET开发的Web Service
- envelope.dotNet = true;
- HttpTransportSE ht = new HttpTransportSE(wsdl);
- try {
- ht.call(SOAP_ACTION, envelope);
- if (envelope.getResponse() != null) {
- SoapObject result = (SoapObject) envelope.bodyIn;
- return result;
- } else {
- return null;
- }
- } catch (Exception e) {
- Log.e("error", e.getMessage());
- }
- return null;
- }
- /**
- *
- * @param result JSON字符串
- * @param name JSON数组名称
- * @param fields JSON字符串所包含的字段
- * @return 返回List<Map<String,Object>>类型的列表,Map<String,Object>对应于 "id":"1"的结构
- */
- public static List<Map<String, Object>> convertJSON2List(String result,
- String name, String[] fields) {
- List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
- try {
- JSONArray array = new JSONObject(result).getJSONArray(name);
- for (int i = 0; i < array.length(); i++) {
- JSONObject object = (JSONObject) array.opt(i);
- Map<String, Object> map = new HashMap<String, Object>();
- for (String str : fields) {
- map.put(str, object.get(str));
- }
- list.add(map);
- }
- } catch (JSONException e) {
- Log.e("error", e.getMessage());
- }
- return list;
- }
- }
Tips:我们都知道C#中给方法加注释,可以按3次“/”,借助于VS就可以自动生成。而在Eclipse当中,可以在方法上面输入“/**”然后按下回车就可以自动生成。
- public class TestWS extends Activity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- RelativeLayout l = new RelativeLayout(this);
- Button button = new Button(l.getContext());
- button.setText("点击本机webservice");
- l.addView(button);
- setContentView(l);
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- final String nameSpace = "http://tempuri.org/";
- final String methodName = "DataTableTest";
- final String wsdl = "http://10.77.137.119:8888/webserviceTest/Service1.asmx?WSDL";
- //调用WebService返回SoapObject对象
- SoapObject soapObject = Util.callWS(nameSpace, methodName,
- wsdl, null);
- if (soapObject != null) {
- //获得soapObject对象的DataTableTestResult属性的值
- String result = soapObject.getProperty(
- "DataTableTestResult").toString();
- Toast.makeText(TestWS.this, result, Toast.LENGTH_SHORT)
- .show();
- try {
- //将JSON字符串转换为List的结构
- List<Map<String, Object>> list = Util.convertJSON2List(
- result, "Result_List", new String[] { "id",
- "name", "email" });
- //通过Intent将List传入到新的Activity
- Intent newIntent = new Intent(TestWS.this,
- GridViewTest.class);
- Bundle bundle = new Bundle();
- //List一定是一个Serializable类型
- bundle.putSerializable("key", (Serializable) list);
- newIntent.putExtras(bundle);
- //启动新的Activity
- startActivity(newIntent);
- } catch (Exception e) {
- e.printStackTrace();
- }
- } else {
- System.out.println("This is null...");
- }
- }
- });
- }
- }
这里面有两点需要注意:
1、这个Activity并没有加载layout布局文件,而是通过代码创建了一个Button,这也是一种创建视图的方法。
2、通过Intent对象,我们将List<Map<String,Object>>传入到了新的Activity当中,这种Intent之间的传值方式需要注意。
- public class GridViewTest extends Activity {
- GridView grid;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_gridview);
- Intent intent = this.getIntent();
- Bundle bundle = intent.getExtras();
- //获得传进来的List<Map<String,Object>>对象
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> list = (List<Map<String, Object>>) bundle
- .getSerializable("key");
- //通过findViewById方法找到GridView对象
- grid = (GridView) findViewById(R.id.grid01);
- //SimpleAdapter适配器填充
- //1.context 当前上下文,用this表示,或者GridViewTest.this
- //2.data A List of Maps.要求是List<Map<String,Object>>结构的列表,即数据源
- //3.resource 布局文件
- //4.from 从哪里来,即提取数据源List中的哪些key
- //5.to 到哪里去,即填充布局文件中的控件
- SimpleAdapter adapter = new SimpleAdapter(this, list,
- R.layout.list_item, new String[] { "id", "name", "email" },
- new int[] { R.id.id, R.id.name, R.id.email });
- //将GridView和适配器绑定
- grid.setAdapter(adapter);
- }
- }
先获得传过来的List对象,然后通过SimpleAdapter绑定到GridView。
activity_gridview.xml 布局文件:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <GridView
- android:id="@+id/grid01"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:horizontalSpacing="1pt"
- android:verticalSpacing="1pt"
- android:numColumns="3"
- android:gravity="center"/>
- </LinearLayout>
list_item.xml 布局文件:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="center_vertical"
- android:orientation="vertical" >
- <TextView
- android:id="@+id/id"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- <TextView
- android:id="@+id/name"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- <TextView
- android:id="@+id/email"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </LinearLayout>
AndroidManifest.xml完整配置:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.webservicedemo"
- android:versionCode="1"
- android:versionName="1.0" >
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="14" />
- <uses-permission android:name="android.permission.INTERNET" />
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name=".TestWS"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <activity
- android:name=".GridViewTest"
- android:label="@string/app_name" >
- </activity>
- </application>
- </manifest>
最终在模拟器上面显示出了从数据库服务器获得的数据:
Android开发系列之调用WebService的更多相关文章
- Android开发中怎样调用系统Email发送邮件(多种调用方式)
在Android中调用其他程序进行相关处理,几乎都是使用的Intent,所以,Email也不例外,所谓的调用Email,只是说Email可以接收Intent并做这些事情 我们都知道,在Android中 ...
- Android开发_如何调用系统默认浏览器访问
Android开发_如何调用系统默认浏览器访问 2015-10-20 17:53 312人阅读 http://blog.sina.com.cn/s/blog_6efce07e010142w7.htm ...
- Android 开发系列教程之(一)Android基础知识
什么是Android Android一词最早是出现在法国作家维里耶德利尔·亚当1986年发表的<未来夏娃>这部科幻小说中,作者利尔·亚当将外表像人类的机器起名为Android,这就是And ...
- 在Android 中使用KSOAP2调用WebService
WebService 是一种基于SOAP协议的远程调用标准.通过WebService可以将不同操作系统平台,不同语言.不同技术整合到一起.在Android SDK中并没有提供调用WebService的 ...
- Android开发系列之SQLite
上篇博客提到过SQLite,它是嵌入式数据库,由于其轻巧但功能强大,被广泛的用于嵌入式设备当中.后来在智能手机.平板流行之后,它作为文件型数据库,几乎成为了智能设备单机数据库的必选,可以随着安卓app ...
- Android开发系列之学习路线图
通过前面的3篇博客已经简单的介绍了Android开发的过程并写了一个简单的demo,了解了Android开发的环境以及一些背景知识. 接下来这篇博客不打算继续学习Android开发的细节,先停一下,明 ...
- android开发系列之aidl
aidl在android开发中的主要作用就是跨进程通讯来着,说到进程相比很多人都是非常熟悉了,但是为什么会有跨进程通讯这个概念呢?原来在android系统中,有这么一套安全机制,为了各个Apk数据的独 ...
- [Android开发系列]IT博客应用
1.关于坑 好吧,在此之前先来说一下,之前开的坑,恩,确实是坑,前面开的两个android开发教程的坑,对不起,实在是没什么动力了,不过源码都有的,大家可以参照github这个应用 https://g ...
- Android开发系列之按钮事件的4种写法
经过前两篇blog的铺垫,我们今天热身一下,做个简单的例子. 目录结构还是引用上篇blog的截图. 具体实现代码: public class MainActivity extends Activity ...
随机推荐
- C#-datagridview设置列宽
在使用datagridview的显示数据的过程中,常常会遇到需要设定datagridview的列宽,这就需要用到datagridview的属性: autosizemode
- DotNet IOC Framework - Microsoft Unity介绍
一. 新建一个ASP.NET MVC4项目 二. 安装Microsoft Unity 1) 管理Nuget程序包 2)安装Unity3程序包 在你的App_Start文件夹里会多出来两个文件 三. 一 ...
- Codeforces Round #323 (Div. 1) B. Once Again... 暴力
B. Once Again... Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/582/probl ...
- 50个Android开发技巧(02 延迟载入和避免反复渲染视图)
当你在Application中创建复杂的布局时.页面的渲染过程也变得更加缓慢. 此时,我们须要利用 <include />标签(避免反复渲染)和 ViewStub类(延迟载入)来优化我们的 ...
- eclipse.ini配置eclipse的启动参数
Eclipse的启动由$ECLIPSE_HOME/eclipse.ini控制,如果$ECLIPSE_HOME 没有被定义,则Eclipse安装目录下的默认eclipse.ini会生效. eclipse ...
- 消息系统Flume与Kafka的区别
首先Flume和Kafka都是消息系统,但是它俩也有着很多不同的地方,Flume更趋向于消息采集系统,而Kafka更趋向于消息缓存系统. [一]设计上的不同 Flume是消息采集系统,它主要解决问题是 ...
- 关于JDBC链接数据库的代码实现
/** * 快速入门 */ @Test public void demo1() { /** * * 1.加载驱动. * * 2.获得连接. * * 3.编写sql执行sql. * * 4.释放资源. ...
- centos find
首先你要确定你的软件是什么方式安装?如果不确定,你可知道你的软件名字,用find查找一下在哪个目录find / -name softname
- wamp 提示 Directive allow_call_time_pass_reference is no longer avaiable in PHP
在wamp运行时,提示"Directive allow_call_time_pass_reference is no longer avaiable in PHP",点击确定之后, ...
- 【转】为 XmlNode.SelectNodes 加上排序功能
测试资料: <Config> <Item a='/> <Item a='/> <Item a='/> <Item a='/> <Ite ...