Ksoap 使用简介

转:http://www.open-open.com/bbs/view/1320111271749?sort=newestjava

 

 

 

WebService 是一种基于SOAP协议的远程调用标准。经过WebService能够将不一样操做系统平台,不一样语言、不一样技术整合到一块儿。在Android SDK中并无提供调用WebService的库,所以,须要使用第三方类库(KSOAP2)来调用WebService。在本文将介绍在Android 中调用WebService的具体细节,并在最后给出一个完整的例子来演示如何使用KSOAP2来调用WebService。android

 

安装第三方类库:KSOAP2
        PC版本的WebService客户端类库很是丰富,例如,Axis二、CXF等,但这些类库对于Android系统过于庞大,也未必很容易移植到 Android系统上。所以,这些开发包并不在咱们考虑的范围内。适合手机的WebService客户端类库也有一些。本例使用了比较经常使用的 KSOAP2。读者能够从以下的地址下载Android版的KSOAP2。

 
       将下载后的jar文件复制到Eclipse工程的lib目录中(若是没有该目录,能够新建一个,固然,也能够放在其余的目录中)。并在Eclipse工程中引用这个jar包,引用后的Eclipse工程目录结构如图1所示。
图1 引用KSOAP2开发包
 
使用KSOAP2调用WebService
       读者可按以下6步来调用WebService的方法。
1. 指定WebService的命名空间和调用的方法名,代码以下:
1 SoapObject request = new SoapObject("http://service", "getName");
    SoapObject类的第1个参数表示WebService的命名空间,能够从WSDL文档中找到WebService的命名空间。第2个参数表示要调用的WebService方法名。
 
2. 设置调用方法的参数值,这一步是可选的,若是方法没有参数,能够省略这一步。设置方法的参数值的代码以下:
1 request.addProperty("param1", "value1"); 
2 request.addProperty("param2", "value2");
   要注意的是,addProperty方法的第1个参数虽然表示调用方法的参数名,但该参数值并不必定与服务端的WebService类中的方法参数名一致,只要设置参数的顺序一致便可。
 
3. 生成调用WebService方法的SOAP请求信息。该信息由SoapSerializationEnvelope对象描述,代码以下:
1 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
2 envelope.bodyOut = request;
 
      建立SoapSerializationEnvelope对象时须要经过SoapSerializationEnvelope类的构造方法设置SOAP协 议的版本号。该版本号须要根据服务端WebService的版本号设置。在建立SoapSerializationEnvelope对象后,不要忘了设置 SoapSerializationEnvelope类的bodyOut属性,该属性的值就是在第1步建立的SoapObject对象。
 
4. 建立HttpTransportSE对象。经过HttpTransportSE类的构造方法能够指定WebService的WSDL文档的URL,代码以下:
1 HttpTransportSE ht =  
2     new HttpTransportSE("http://192.168.17.156:8080/axis2/services/SearchProductService?wsdl");
5. 使用call方法调用WebService方法,代码以下:
 
1 ht.call(null, envelope);
call方法的第1个参数通常为null,第2个参数就是在第3步建立的SoapSerializationEnvelope对象。
 
6. 使用getResponse方法得到WebService方法的返回结果,代码以下:
1 SoapObject soapObject = (SoapObject) envelope.getResponse();
示例:经过WebService查询产品信息
        本例涉及到一个WebService服务端程序和一个OPhone客户端程序。读者可直接将服务端程序(axis2目录)复制到<Tomcat安装目录>\webapps目录中,而后启动Tomcat,并在浏览器地址栏中输入以下的URL:
http://localhost:8080/axis2
 
        若是在浏览器中显示如图2所示的页面,说明服务端程序已经安装成功。
surface view2.png
图2 WebService主页面
 
        这个服务端WebService程序是SearchProductService,实际上SearchProductService是一个Java类,只 是利用Axis2将其映射成WebService。在该类中有一个getProduct方法。这个方法有一个String类型的参数,表示产品名称。该方 法返回一个Product对象,该对象有3个属性:name、price和productNumber。读者可使用以下的URL来查看 SearchProductService的WSDL文档。
http://localhost:8080/axis2/services/SearchProductService?wsdl
 
       显示WSDL文档的页面如图3所示。
surface view3.png
图3 WSDL文档
 
         在图3中的黑框中就是WebService的命名空间,也是SoapObject类的构造方法的第1个参数值。这个WebService程序能够直接使用以下的URL进行测试。
http://localhost:8080/axis2/services/SearchProductService/getProduct?param0=iphone
 
        测试的结果如图4所示。
surface view4.png
图4 测试getProduct方法
 
        从图4所示的测试结果能够看出,Axis2将getProduct方法返回的Product对象直接转换成了XML文档(其实是SOAP格式)返回。
 
       下面咱们来根据前面介绍的使用KSOAP2的步骤来编写调用WebService的OPhone客户端程序,代码以下:
01 package net.blogjava.mobile.wsclient; 
02     
03 import org.ksoap2.SoapEnvelope; 
04 import org.ksoap2.serialization.SoapObject; 
05 import org.ksoap2.serialization.SoapSerializationEnvelope; 
06 import org.ksoap2.transport.HttpTransportSE; 
07 import android.app.Activity; 
08 import android.os.Bundle; 
09 import android.view.View; 
10 import android.view.View.OnClickListener; 
11 import android.widget.Button; 
12 import android.widget.EditText; 
13 import android.widget.TextView; 
14     
15 public class Main extends Activity implements OnClickListener 
16
17     @Override 
18     public void onClick(View view) 
19     
20         EditText etProductName = (EditText)findViewById(R.id.etProductName); 
21         TextView tvResult = (TextView)findViewById(R.id.tvResult); 
22         // WSDL文档的URL,192.168.17.156为PC的ID地址 
23         String serviceUrl = "http://192.168.17.156:8080/axis2/services/SearchProductService?wsdl"
24         // 定义调用的WebService方法名 
25         String methodName = "getProduct"
26         // 第1步:建立SoapObject对象,并指定WebService的命名空间和调用的方法名 
27         SoapObject request = new SoapObject("http://service", methodName); 
28         // 第2步:设置WebService方法的参数 
29         request.addProperty("productName", etProductName.getText().toString()); 
30         // 第3步:建立SoapSerializationEnvelope对象,并指定WebService的版本 
31         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
32         // 设置bodyOut属性 
33         envelope.bodyOut = request; 
34         // 第4步:建立HttpTransportSE对象,并指定WSDL文档的URL 
35         HttpTransportSE ht = new HttpTransportSE(serviceUrl);         
36         try 
37         {  
38             // 第5步:调用WebService 
39             ht.call(null, envelope); 
40             if (envelope.getResponse() != null
41             
42                 // 第6步:使用getResponse方法得到WebService方法的返回结果 
43                 SoapObject soapObject = (SoapObject) envelope.getResponse(); 
44                 // 经过getProperty方法得到Product对象的属性值 
45                 String result = "产品名称:" + soapObject.getProperty("name") + "\n"
46                 result += "产品数量:" + soapObject.getProperty("productNumber") + "\n"
47                 result += "产品价格:" + soapObject.getProperty("price"); 
48                 tvResult.setText(result); 
49     
50             
51             else 
52                 tvResult.setText("无此产品."); 
53             
54         
55         catch (Exception e) 
56         
57         
58     
59     @Override 
60     public void onCreate(Bundle savedInstanceState) 
61     
62         super.onCreate(savedInstanceState); 
63         setContentView(R.layout.main); 
64         Button btnSearch = (Button) findViewById(R.id.btnSearch); 
65         btnSearch.setOnClickListener(this); 
66     
67 }
   在编写上面代码时应注意以下两点:
 
  • 在 第2步中addProperty方法的第1个参数值是productName,该值虽然是getProduct方法的参数名,但addProperty方 法的第1个参数值并不限于productName,读者能够将这个参数设为其余的任何字符串(但该值必须在XML中是合法的,例如,不是设为 “<”、“>”等XML预留的字符串)。
  • 经过SoapObject类的getProperty方法能够得到Product对象的属性值,这些属性名就是图4所示的测试结果中的属性名。
        运行本例,在文本框中输入“htc hero”,单击【查询】按钮,会在按钮下方显示如图5所示的查询结果。
 
surface view5.png
图5  显示查询结果
防止UI组件阻塞
        从功能上看,本文示例中给出的代码并无任何问题。但可能有的读者会有这样的担忧:若是调用WebService的用户不少,至使服务端响应迟缓;或服务 端的IP根本就不对,那么在这些状况下,用户界面的按钮和文本框组件岂不是象“死”了同样没法响应用户的其余动做。固然,发生这种状况的可能性是有的,尤 其是在复杂的网络环境中发生的可能性是很大的,一但发生这种事情,就会使整个软件系统在用户体验上变得很是糟糕。
用户和开发人员都但愿改善这种糟糕的状况。最理想的状态是单击按钮调用WebService方法时,即便因为某种缘由,WebService方法并未当即返回,界面上的组件仍然会处于活动状态,也就是说,用户仍然可使用当前界面中的其余组件。
 
         在OPhone中能够采用异步的方式来达到这个目的。异步实际上就是经过多线程的方式来实现。通常使用new Thread(this).start()来建立和开始一个线程。但本节并不使用Thread来实现异步,而是经过AsyncTask类使要执行的任务 (调用WebService)在后台执行。
 
        下面先看看改进后的代码。
 
01 package net.blogjava.mobile.wsclient; 
02     
03 import org.ksoap2.SoapEnvelope; 
04 import org.ksoap2.serialization.SoapObject; 
05 import org.ksoap2.serialization.SoapSerializationEnvelope; 
06 import org.ksoap2.transport.HttpTransportSE; 
07 import android.app.Activity; 
08 import android.os.AsyncTask; 
09 import android.os.Bundle; 
10 import android.view.View; 
11 import android.view.View.OnClickListener; 
12 import android.widget.Button; 
13 import android.widget.EditText; 
14 import android.widget.TextView; 
15     
16 public class Main extends Activity implements OnClickListener 
17
18     private EditText etProductName; 
19     private TextView tvResult; 
20     
21     class WSAsyncTask extends AsyncTask 
22     
23         String result = ""
24         @Override 
25         protected Object doInBackground(Object... params) 
26         
27             try 
28             
29                 String serviceUrl = "http://192.168.17.156:8080/axis2/services/SearchProductService?wsdl"
30                 String methodName = "getProduct"
31                 SoapObject request = new SoapObject("http://service"
32                         methodName); 
33                 request.addProperty("productName", etProductName.getText().toString()); 
34                 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( 
35                         SoapEnvelope.VER11); 
36                 envelope.bodyOut = request; 
37                 HttpTransportSE ht = new HttpTransportSE(serviceUrl); 
38     
39                 ht.call(null, envelope); 
40                 if (envelope.getResponse() != null
41                 
42                     SoapObject soapObject = (SoapObject) envelope.getResponse(); 
43                     result = "产品名称:" + soapObject.getProperty("name") + "\n"
44                     result += "产品数量:" + soapObject.getProperty("productNumber"
45                             + "\n"
46                     result += "产品价格:" + soapObject.getProperty("price"); 
47     
48                 
49                 else 
50                 
51                     result = "无此产品."
52                 
53             
54             catch (Exception e) 
55             
56                 result = "调用WebService错误."
57             
58             // 必须使用post方法更新UI组件 
59             tvResult.post(new Runnable() 
60             
61                 @Override 
62                 public void run() 
63                 
64                     tvResult.setText(result); 
65     
66                 
67             }); 
68             return null
69         
70     
71     
72     @Override 
73     public void onClick(View view) 
74
75     // 异步执行调用WebService的任务   
76         new WSAsyncTask().execute(); 
77     
78     @Override 
79     public void onCreate(Bundle savedInstanceState) 
80     
81         super.onCreate(savedInstanceState); 
82         setContentView(R.layout.main); 
83         Button btnSearch = (Button) findViewById(R.id.btnSearch); 
84         btnSearch.setOnClickListener(this); 
85         etProductName = (EditText) findViewById(R.id.etProductName); 
86         tvResult = (TextView) findViewById(R.id.tvResult); 
87     
88     
89 }
     调用WebService的核心代码与示例中的代码彻底同样,在这里就再也不作具体的介绍了。但在编写上面的代码时还须要注意以下几点。
 
1. 通常须要编写一个AsyncTask的子类来完成后台执行任务的工做。
2.  AsyncTask的核心方法是doInBackground,当调用AsyncTask类的execute方法时,doInBackground方法会异步执行。所以,能够将执行任务的代码写在doInBackground方法中。
3. 由 于本例中的TextView组件是在主线程(UI线程)中建立的,所以,在其余的线程(doInBackground方法所在的线程)中不能直接更新 TextVew组件。为了更新TextView组件,须要使用TextView类的post方法。该方法的参数是一个Runnable对象,须要将更新 TextView组件的代码写在Runnable接口的run方法中。
4. 虽然不能在其余线程中更新UI组件,但能够从其余线程直接读取UI组件的值。例如,在doInBackground方法中直接读取了EditText组件的值。
5. 调用AsyncTask类的execute方法后会当即返回。execute方法的参数就是doInBackground方法的参数。doInBackground方法的返回值能够经过AsyncTask.execute(...).get()方法得到。
读者能够将本例中的IP改为其余的值,看看单击按钮后,是否还可在文本框中输入其余的内容。若是这个IP是正确的,而且WebService可访问,那么会在TextView组件中输出相应的返回值。
 
总结
       本文主要介绍了如何使用KSOAP2来调用WebService。KSOAP2是第三方开发的专门用于在移动设备调用WebService的类库。使用 KSOAP2调用WebService可分为6步来完成,其中主要使用了SoapObject对象来指定了要调用的方法,而后经过 HttpTransportSE对象的call方法来调用WebService的方法,最后经过getResponse方法返回结果。读者能够经过本文提 供的完整示例来体会使用KSOAP2调用WebService的完整过程。在最后还介绍了如何经过异步调用WebService的方式来防止因服务端故障 或其余缘由致使的UI组件阻塞。
相关文章
相关标签/搜索