标签:
我在学习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中显示
我们先提供一个助手类,这是我自己动手封装了一下这两个操作所需要的方法。
- public final class Util {
-
- 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;
-
-
- 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;
- }
-
-
- 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";
-
-
- SoapObject soapObject = Util.callWS(nameSpace, methodName,
- wsdl, null);
- if (soapObject != null) {
-
-
- String result = soapObject.getProperty(
- "DataTableTestResult").toString();
-
- Toast.makeText(TestWS.this, result, Toast.LENGTH_SHORT)
- .show();
-
- try {
-
- List<Map<String, Object>> list = Util.convertJSON2List(
- result, "Result_List", new String[] { "id",
- "name", "email" });
-
-
- Intent newIntent = new Intent(TestWS.this,
- GridViewTest.class);
- Bundle bundle = new Bundle();
-
-
- bundle.putSerializable("key", (Serializable) list);
- newIntent.putExtras(bundle);
-
-
- 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();
-
-
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> list = (List<Map<String, Object>>) bundle
- .getSerializable("key");
-
-
- grid = (GridView) findViewById(R.id.grid01);
-
-
-
-
-
-
-
- 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 });
-
-
- 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
标签:
原文地址:http://www.cnblogs.com/guwei4037/p/5582933.html