Android服务开发——WebService

我在学习Android开发过程中遇到的第一个疑问就是Android客户端是怎么跟服务器数据库进行交互的呢?这个问题是我当初初次接触Android时所困扰我的一个很大的问题,直到几年前的一天,我突然想到WebService是否可以呢?让WebService充当服务器端的角色,完成与服务器数据库操作相关的事情,而Android客户端只要按照WebService方法参数的要求去调用就行了。在当时我对这个解决方案的实现还没模糊,我想这个问题也是初学Android的朋友肯定会想到的问题。那么现在就让我们动手去实现它吧。

这个程序我们演示如何请求Web Service来获取服务端提供的数据。

由于我对C#比较熟悉,所以我优先使用自己熟悉的技术来搭建WebService的项目。很简单我们就用VS工具创建一个Web服务应用程序(VS2008,而从VS2010开始优先使用WCF来创建服务应用程序了,不过用WCF框架创建WebService也是很容易的)。

 

[csharp]  view plain  copy
 
  1. [WebMethod]  
  2. public string DataTableTest()  
  3. {  
  4.     DataTable dt = new DataTable("userTable");  
  5.     dt.Columns.Add("id",typeof(int));  
  6.     dt.Columns.Add("name", typeof(string));  
  7.     dt.Columns.Add("email", typeof(string));  
  8.   
  9.     dt.Rows.Add(1, "gary.gu", "guwei4037@sina.com");  
  10.     dt.Rows.Add(2, "jinyingying", "345822155@qq.com");  
  11.     dt.Rows.Add(3, "jinyingying", "345822155@qq.com");  
  12.     dt.Rows.Add(4, "jinyingying", "345822155@qq.com");  
  13.   
  14.     return Util.CreateJsonParameters(dt);  
  15. }  

这个WebService的方法很简单,就是组建一个DataTable的数据类型,并通过CreateJsonParameters方法转化为JSON字符串。这里面的DataTable可以修改成从数据库端读取数据到DataTable对象。

 

 

[csharp]  view plain  copy
 
  1. public static string CreateJsonParameters(DataTable dt)  
  2. {  
  3.     StringBuilder JsonString = new StringBuilder();  
  4.     if (dt != null && dt.Rows.Count > 0)  
  5.     {  
  6.         JsonString.Append("{ ");  
  7.         JsonString.Append("\"Result_List\":[ ");  
  8.         for (int i = 0; i < dt.Rows.Count; i++)  
  9.         {  
  10.             JsonString.Append("{ ");  
  11.             for (int j = 0; j < dt.Columns.Count; j++)  
  12.             {  
  13.                 if (j < dt.Columns.Count - 1)  
  14.                 {  
  15.                     JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");  
  16.                 }  
  17.                 else if (j == dt.Columns.Count - 1)  
  18.                 {  
  19.                     JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");  
  20.                 }  
  21.             }  
  22.             if (i == dt.Rows.Count - 1)  
  23.             {  
  24.                 JsonString.Append("} ");  
  25.             }  
  26.             else  
  27.             {  
  28.                 JsonString.Append("}, ");  
  29.             }  
  30.         }  
  31.         JsonString.Append("]}");  
  32.         return JsonString.ToString();  
  33.     }  
  34.     else  
  35.     {  
  36.         return null;  
  37.     }  
  38. }  

这个方法是我从网上随便找到的一个方法,比较土了,就是直接拼接JSON字符串(无所谓,这不是我们要关心的重点)。

 

WebService端准备好,就可以将其发布到IIS。发布方法跟网站一样,如果是本机的话,可以直接测试WebService方法返回得到的结果,比如调用后会得到如下结果:

这里肯定有人问,这外面是XML,里面又是JSON,这不是“四不像”吗?是的,我这样做是想说明一点,WebService是基于Soap的,数据传输的格式就是XML,所以这里得到XML文档是理所当然。如果你想得到纯净的JSON字符串,可以使用C#中的WCF框架(可以指定客户端返回JSON格式)或者Java中的Servlet(直接刷出JSON文本)。

好,接下来我们要做两件事:

1、请求这个WebService得到这个JSON字符串

2、格式化这个JSON字符串在Android中显示

我们先提供一个助手类,这是我自己动手封装了一下这两个操作所需要的方法。

 

[java]  view plain  copy
 
  1. /** 
  2.  * @author gary.gu 助手类 
  3.  */  
  4. public final class Util {  
  5.     /** 
  6.      * @param nameSpace  WS的命名空间 
  7.      * @param methodName WS的方法名 
  8.      * @param wsdl       WS的wsdl的完整路径名 
  9.      * @param params     WS的方法所需要的参数 
  10.      * @return           SoapObject对象 
  11.      */  
  12.     public static SoapObject callWS(String nameSpace, String methodName,  
  13.             String wsdl, Map<String, Object> params) {  
  14.         final String SOAP_ACTION = nameSpace + methodName;  
  15.         SoapObject soapObject = new SoapObject(nameSpace, methodName);  
  16.   
  17.         if ((params != null) && (!params.isEmpty())) {  
  18.             Iterator<Entry<String, Object>> it = params.entrySet().iterator();  
  19.             while (it.hasNext()) {  
  20.                 Map.Entry<String, Object> e = (Map.Entry<String, Object>) it  
  21.                         .next();  
  22.                 soapObject.addProperty(e.getKey(), e.getValue());  
  23.             }  
  24.         }  
  25.   
  26.         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
  27.                 SoapEnvelope.VER11);  
  28.         envelope.bodyOut = soapObject;  
  29.           
  30.         // 兼容.NET开发的Web Service  
  31.         envelope.dotNet = true;  
  32.   
  33.         HttpTransportSE ht = new HttpTransportSE(wsdl);  
  34.         try {  
  35.             ht.call(SOAP_ACTION, envelope);  
  36.             if (envelope.getResponse() != null) {  
  37.                 SoapObject result = (SoapObject) envelope.bodyIn;  
  38.                 return result;  
  39.             } else {  
  40.                 return null;  
  41.             }  
  42.         } catch (Exception e) {  
  43.             Log.e("error", e.getMessage());  
  44.         }  
  45.         return null;  
  46.     }  
  47.   
  48.     /** 
  49.      *  
  50.      * @param result JSON字符串 
  51.      * @param name   JSON数组名称 
  52.      * @param fields JSON字符串所包含的字段 
  53.      * @return       返回List<Map<String,Object>>类型的列表,Map<String,Object>对应于 "id":"1"的结构 
  54.      */  
  55.     public static List<Map<String, Object>> convertJSON2List(String result,  
  56.             String name, String[] fields) {  
  57.         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  58.         try {  
  59.             JSONArray array = new JSONObject(result).getJSONArray(name);  
  60.   
  61.             for (int i = 0; i < array.length(); i++) {  
  62.                 JSONObject object = (JSONObject) array.opt(i);  
  63.                 Map<String, Object> map = new HashMap<String, Object>();  
  64.                 for (String str : fields) {  
  65.                     map.put(str, object.get(str));  
  66.                 }  
  67.                 list.add(map);  
  68.             }  
  69.         } catch (JSONException e) {  
  70.             Log.e("error", e.getMessage());  
  71.         }  
  72.         return list;  
  73.     }  
  74. }  

Tips:我们都知道C#中给方法加注释,可以按3次“/”,借助于VS就可以自动生成。而在Eclipse当中,可以在方法上面输入“/**”然后按下回车就可以自动生成。

 

 

[java]  view plain  copy
 
  1. public class TestWS extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.   
  7.         RelativeLayout l = new RelativeLayout(this);  
  8.         Button button = new Button(l.getContext());  
  9.         button.setText("点击本机webservice");  
  10.         l.addView(button);  
  11.         setContentView(l);  
  12.   
  13.         button.setOnClickListener(new View.OnClickListener() {  
  14.   
  15.             @Override  
  16.             public void onClick(View v) {  
  17.   
  18.                 final String nameSpace = "http://tempuri.org/";  
  19.                 final String methodName = "DataTableTest";  
  20.                 final String wsdl = "http://10.77.137.119:8888/webserviceTest/Service1.asmx?WSDL";  
  21.   
  22.                 //调用WebService返回SoapObject对象  
  23.                 SoapObject soapObject = Util.callWS(nameSpace, methodName,  
  24.                         wsdl, null);  
  25.                 if (soapObject != null) {  
  26.                       
  27.                     //获得soapObject对象的DataTableTestResult属性的值  
  28.                     String result = soapObject.getProperty(  
  29.                             "DataTableTestResult").toString();  
  30.   
  31.                     Toast.makeText(TestWS.this, result, Toast.LENGTH_SHORT)  
  32.                             .show();  
  33.   
  34.                     try {  
  35.                         //将JSON字符串转换为List的结构  
  36.                         List<Map<String, Object>> list = Util.convertJSON2List(  
  37.                                 result, "Result_List", new String[] { "id",  
  38.                                         "name", "email" });  
  39.   
  40.                         //通过Intent将List传入到新的Activity  
  41.                         Intent newIntent = new Intent(TestWS.this,  
  42.                                 GridViewTest.class);  
  43.                         Bundle bundle = new Bundle();  
  44.                           
  45.                         //List一定是一个Serializable类型  
  46.                         bundle.putSerializable("key", (Serializable) list);  
  47.                         newIntent.putExtras(bundle);  
  48.                           
  49.                         //启动新的Activity  
  50.                         startActivity(newIntent);  
  51.   
  52.                     } catch (Exception e) {  
  53.                         e.printStackTrace();  
  54.                     }  
  55.                 } else {  
  56.                     System.out.println("This is null...");  
  57.                 }  
  58.             }  
  59.         });  
  60.     }  
  61.   
  62. }  

 

这里面有两点需要注意:

1、这个Activity并没有加载layout布局文件,而是通过代码创建了一个Button,这也是一种创建视图的方法。

2、通过Intent对象,我们将List<Map<String,Object>>传入到了新的Activity当中,这种Intent之间的传值方式需要注意。

 

[java]  view plain  copy
 
  1. public class GridViewTest extends Activity {  
  2.   
  3.     GridView grid;  
  4.   
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.activity_gridview);  
  9.   
  10.         Intent intent = this.getIntent();  
  11.         Bundle bundle = intent.getExtras();  
  12.   
  13.         //获得传进来的List<Map<String,Object>>对象  
  14.         @SuppressWarnings("unchecked")  
  15.         List<Map<String, Object>> list = (List<Map<String, Object>>) bundle  
  16.                 .getSerializable("key");  
  17.   
  18.         //通过findViewById方法找到GridView对象  
  19.         grid = (GridView) findViewById(R.id.grid01);  
  20.           
  21.         //SimpleAdapter适配器填充  
  22.         //1.context    当前上下文,用this表示,或者GridViewTest.this  
  23.         //2.data       A List of Maps.要求是List<Map<String,Object>>结构的列表,即数据源  
  24.         //3.resource   布局文件  
  25.         //4.from       从哪里来,即提取数据源List中的哪些key  
  26.         //5.to         到哪里去,即填充布局文件中的控件  
  27.         SimpleAdapter adapter = new SimpleAdapter(this, list,  
  28.                 R.layout.list_item, new String[] { "id", "name", "email" },  
  29.                 new int[] { R.id.id, R.id.name, R.id.email });  
  30.           
  31.         //将GridView和适配器绑定  
  32.         grid.setAdapter(adapter);  
  33.     }  
  34.   
  35. }  

先获得传过来的List对象,然后通过SimpleAdapter绑定到GridView。

 

activity_gridview.xml 布局文件:

 

[html]  view plain  copy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.       
  7.     <GridView   
  8.         android:id="@+id/grid01"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:horizontalSpacing="1pt"  
  12.         android:verticalSpacing="1pt"  
  13.         android:numColumns="3"  
  14.         android:gravity="center"/>  
  15.   
  16. </LinearLayout>  

list_item.xml 布局文件:

 

 

[html]  view plain  copy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:gravity="center_vertical"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <TextView  
  9.         android:id="@+id/id"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content" />  
  12.   
  13.     <TextView  
  14.         android:id="@+id/name"  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content" />  
  17.   
  18.     <TextView  
  19.         android:id="@+id/email"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content" />  
  22.   
  23. </LinearLayout>  

AndroidManifest.xml完整配置:

 

 

[html]  view plain  copy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.webservicedemo"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="14" />  
  10.   
  11.     <uses-permission android:name="android.permission.INTERNET" />  
  12.   
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name=".TestWS"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.   
  24.                 <category android:name="android.intent.category.LAUNCHER" />  
  25.             </intent-filter>  
  26.         </activity>  
  27.         <activity  
  28.             android:name=".GridViewTest"  
  29.             android:label="@string/app_name" >  
  30.         </activity>  
  31.     </application>  
  32.   
  33. </manifest>  

 

最终在模拟器上面显示出了从数据库服务器获得的数据:

 

转载于:https://www.cnblogs.com/guwei4037/p/5582933.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值