天天看点

Ksoap 使用简介

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

WebService 是一种基于SOAP协议的远程调用标准。通过WebService可以将不同操作系统平台,不同语言、不同技术整合到一起。在Android SDK中并没有提供调用WebService的库,因此,需要使用第三方类库(KSOAP2)来调用WebService。在本文将介绍在Android 中调用WebService的具体细节,并在最后给出一个完整的例子来演示如何使用KSOAP2来调用WebService。

安装第三方类库:KSOAP2

        PC版本的WebService客户端类库非常丰富,例如,Axis2、CXF等,但这些类库对于Android系统过于庞大,也未必很容易移植到 Android系统上。因此,这些开发包并不在我们考虑的范围内。适合手机的WebService客户端类库也有一些。本例使用了比较常用的 KSOAP2。读者可以从如下的地址下载Android版的KSOAP2。

       将下载后的jar文件复制到Eclipse工程的lib目录中(如果没有该目录,可以新建一个,当然,也可以放在其他的目录中)。并在Eclipse工程中引用这个jar包,引用后的Eclipse工程目录结构如图1所示。

图1 引用KSOAP2开发包

使用KSOAP2调用WebService

       读者可按如下6步来调用WebService的方法。

1. 指定WebService的命名空间和调用的方法名,代码如下:

<code>1</code>

<code>SoapObject request =</code><code>new</code> <code>SoapObject(</code><code>"http://service"</code><code>,</code><code>"getName"</code><code>);</code>

    SoapObject类的第1个参数表示WebService的命名空间,可以从WSDL文档中找到WebService的命名空间。第2个参数表示要调用的WebService方法名。

2. 设置调用方法的参数值,这一步是可选的,如果方法没有参数,可以省略这一步。设置方法的参数值的代码如下:

<code>request.addProperty(</code><code>"param1"</code><code>,</code><code>"value1"</code><code>); </code>

<code>2</code>

<code>request.addProperty(</code><code>"param2"</code><code>,</code><code>"value2"</code><code>);</code>

   要注意的是,addProperty方法的第1个参数虽然表示调用方法的参数名,但该参数值并不一定与服务端的WebService类中的方法参数名一致,只要设置参数的顺序一致即可。

3. 生成调用WebService方法的SOAP请求信息。该信息由SoapSerializationEnvelope对象描述,代码如下:

<code>SoapSerializationEnvelope envelope =</code><code>new</code> <code>SoapSerializationEnvelope(SoapEnvelope.VER11); </code>

<code>envelope.bodyOut = request;</code>

      创建SoapSerializationEnvelope对象时需要通过SoapSerializationEnvelope类的构造方法设置SOAP协 议的版本号。该版本号需要根据服务端WebService的版本号设置。在创建SoapSerializationEnvelope对象后,不要忘了设置 SoapSerializationEnvelope类的bodyOut属性,该属性的值就是在第1步创建的SoapObject对象。

4. 创建HttpTransportSE对象。通过HttpTransportSE类的构造方法可以指定WebService的WSDL文档的URL,代码如下:

<code>HttpTransportSE ht =  </code>

<code>    </code><code>new</code> <code>HttpTransportSE(</code><code>"http://192.168.17.156:8080/axis2/services/SearchProductService?wsdl"</code><code>);</code>

5. 使用call方法调用WebService方法,代码如下:

<code>ht.call(</code><code>null</code><code>, envelope);</code>

call方法的第1个参数一般为null,第2个参数就是在第3步创建的SoapSerializationEnvelope对象。

6. 使用getResponse方法获得WebService方法的返回结果,代码如下:

<code>SoapObject soapObject = (SoapObject) envelope.getResponse();</code>

示例:通过WebService查询产品信息

        本例涉及到一个WebService服务端程序和一个OPhone客户端程序。读者可直接将服务端程序(axis2目录)复制到&lt;Tomcat安装目录&gt;\webapps目录中,然后启动Tomcat,并在浏览器地址栏中输入如下的URL:

http://localhost:8080/axis2

        如果在浏览器中显示如图2所示的页面,说明服务端程序已经安装成功。

Ksoap 使用简介

图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所示。

Ksoap 使用简介

图3 WSDL文档

         在图3中的黑框中就是WebService的命名空间,也是SoapObject类的构造方法的第1个参数值。这个WebService程序可以直接使用如下的URL进行测试。

http://localhost:8080/axis2/services/SearchProductService/getProduct?param0=iphone

        测试的结果如图4所示。

Ksoap 使用简介

图4 测试getProduct方法

        从图4所示的测试结果可以看出,Axis2将getProduct方法返回的Product对象直接转换成了XML文档(实际上是SOAP格式)返回。

       下面我们来根据前面介绍的使用KSOAP2的步骤来编写调用WebService的OPhone客户端程序,代码如下:

<code>01</code>

<code>package</code> <code>net.blogjava.mobile.wsclient; </code>

<code>02</code>

<code>   </code> 

<code>03</code>

<code>import</code> <code>org.ksoap2.SoapEnvelope; </code>

<code>04</code>

<code>import</code> <code>org.ksoap2.serialization.SoapObject; </code>

<code>05</code>

<code>import</code> <code>org.ksoap2.serialization.SoapSerializationEnvelope; </code>

<code>06</code>

<code>import</code> <code>org.ksoap2.transport.HttpTransportSE; </code>

<code>07</code>

<code>import</code> <code>android.app.Activity; </code>

<code>08</code>

<code>import</code> <code>android.os.Bundle; </code>

<code>09</code>

<code>import</code> <code>android.view.View; </code>

<code>10</code>

<code>import</code> <code>android.view.View.OnClickListener; </code>

<code>11</code>

<code>import</code> <code>android.widget.Button; </code>

<code>12</code>

<code>import</code> <code>android.widget.EditText; </code>

<code>13</code>

<code>import</code> <code>android.widget.TextView; </code>

<code>14</code>

<code>15</code>

<code>public</code> <code>class</code> <code>Main</code><code>extends</code> <code>Activity</code><code>implements</code> <code>OnClickListener </code>

<code>16</code>

<code>{ </code>

<code>17</code>

<code>    </code><code>@Override</code> 

<code>18</code>

<code>    </code><code>public</code> <code>void</code> <code>onClick(View view) </code>

<code>19</code>

<code>    </code><code>{ </code>

<code>20</code>

<code>        </code><code>EditText etProductName = (EditText)findViewById(R.id.etProductName); </code>

<code>21</code>

<code>        </code><code>TextView tvResult = (TextView)findViewById(R.id.tvResult); </code>

<code>22</code>

<code>        </code><code>// WSDL文档的URL,192.168.17.156为PC的ID地址 </code>

<code>23</code>

<code>        </code><code>String serviceUrl =</code><code>"http://192.168.17.156:8080/axis2/services/SearchProductService?wsdl"</code><code>; </code>

<code>24</code>

<code>        </code><code>// 定义调用的WebService方法名 </code>

<code>25</code>

<code>        </code><code>String methodName =</code><code>"getProduct"</code><code>; </code>

<code>26</code>

<code>        </code><code>// 第1步:创建SoapObject对象,并指定WebService的命名空间和调用的方法名 </code>

<code>27</code>

<code>        </code><code>SoapObject request =</code><code>new</code> <code>SoapObject(</code><code>"http://service"</code><code>, methodName); </code>

<code>28</code>

<code>        </code><code>// 第2步:设置WebService方法的参数 </code>

<code>29</code>

<code>        </code><code>request.addProperty(</code><code>"productName"</code><code>, etProductName.getText().toString()); </code>

<code>30</code>

<code>        </code><code>// 第3步:创建SoapSerializationEnvelope对象,并指定WebService的版本 </code>

<code>31</code>

<code>        </code><code>SoapSerializationEnvelope envelope =</code><code>new</code> <code>SoapSerializationEnvelope(SoapEnvelope.VER11); </code>

<code>32</code>

<code>        </code><code>// 设置bodyOut属性 </code>

<code>33</code>

<code>        </code><code>envelope.bodyOut = request; </code>

<code>34</code>

<code>        </code><code>// 第4步:创建HttpTransportSE对象,并指定WSDL文档的URL </code>

<code>35</code>

<code>        </code><code>HttpTransportSE ht =</code><code>new</code> <code>HttpTransportSE(serviceUrl);         </code>

<code>36</code>

<code>        </code><code>try</code> 

<code>37</code>

<code>        </code><code>{  </code>

<code>38</code>

<code>            </code><code>// 第5步:调用WebService </code>

<code>39</code>

<code>            </code><code>ht.call(</code><code>null</code><code>, envelope); </code>

<code>40</code>

<code>            </code><code>if</code> <code>(envelope.getResponse() !=</code><code>null</code><code>) </code>

<code>41</code>

<code>            </code><code>{ </code>

<code>42</code>

<code>                </code><code>// 第6步:使用getResponse方法获得WebService方法的返回结果 </code>

<code>43</code>

<code>                </code><code>SoapObject soapObject = (SoapObject) envelope.getResponse(); </code>

<code>44</code>

<code>                </code><code>// 通过getProperty方法获得Product对象的属性值 </code>

<code>45</code>

<code>                </code><code>String result =</code><code>"产品名称:"</code> <code>+ soapObject.getProperty(</code><code>"name"</code><code>) +</code><code>"\n"</code><code>; </code>

<code>46</code>

<code>                </code><code>result +=</code><code>"产品数量:"</code> <code>+ soapObject.getProperty(</code><code>"productNumber"</code><code>) +</code><code>"\n"</code><code>; </code>

<code>47</code>

<code>                </code><code>result +=</code><code>"产品价格:"</code> <code>+ soapObject.getProperty(</code><code>"price"</code><code>); </code>

<code>48</code>

<code>                </code><code>tvResult.setText(result); </code>

<code>49</code>

<code>50</code>

<code>            </code><code>} </code>

<code>51</code>

<code>            </code><code>else</code> <code>{ </code>

<code>52</code>

<code>                </code><code>tvResult.setText(</code><code>"无此产品."</code><code>); </code>

<code>53</code>

<code>54</code>

<code>        </code><code>} </code>

<code>55</code>

<code>        </code><code>catch</code> <code>(Exception e) </code>

<code>56</code>

<code>        </code><code>{ </code>

<code>57</code>

<code>58</code>

<code>    </code><code>} </code>

<code>59</code>

<code>60</code>

<code>    </code><code>public</code> <code>void</code> <code>onCreate(Bundle savedInstanceState) </code>

<code>61</code>

<code>62</code>

<code>        </code><code>super</code><code>.onCreate(savedInstanceState); </code>

<code>63</code>

<code>        </code><code>setContentView(R.layout.main); </code>

<code>64</code>

<code>        </code><code>Button btnSearch = (Button) findViewById(R.id.btnSearch); </code>

<code>65</code>

<code>        </code><code>btnSearch.setOnClickListener(</code><code>this</code><code>); </code>

<code>66</code>

<code>67</code>

<code>}</code>

   在编写上面代码时应注意如下两点:

在 第2步中addProperty方法的第1个参数值是productName,该值虽然是getProduct方法的参数名,但addProperty方 法的第1个参数值并不限于productName,读者可以将这个参数设为其他的任何字符串(但该值必须在XML中是合法的,例如,不是设为 “&lt;”、“&gt;”等XML预留的字符串)。

通过SoapObject类的getProperty方法可以获得Product对象的属性值,这些属性名就是图4所示的测试结果中的属性名。

        运行本例,在文本框中输入“htc hero”,单击【查询】按钮,会在按钮下方显示如图5所示的查询结果。

Ksoap 使用简介

图5  显示查询结果

防止UI组件阻塞

        从功能上看,本文示例中给出的代码并没有任何问题。但可能有的读者会有这样的担心:如果调用WebService的用户很多,至使服务端响应迟缓;或服务 端的IP根本就不对,那么在这些情况下,用户界面的按钮和文本框组件岂不是象“死”了一样无法响应用户的其他动作。当然,发生这种情况的可能性是有的,尤 其是在复杂的网络环境中发生的可能性是很大的,一但发生这种事情,就会使整个软件系统在用户体验上变得非常糟糕。

用户和开发人员都希望改善这种糟糕的情况。最理想的状态是单击按钮调用WebService方法时,即使由于某种原因,WebService方法并未立即返回,界面上的组件仍然会处于活动状态,也就是说,用户仍然可以使用当前界面中的其他组件。

         在OPhone中可以采用异步的方式来达到这个目的。异步实际上就是通过多线程的方式来实现。一般使用new Thread(this).start()来创建和开始一个线程。但本节并不使用Thread来实现异步,而是通过AsyncTask类使要执行的任务 (调用WebService)在后台执行。

        下面先看看改进后的代码。

<code>import</code> <code>android.os.AsyncTask; </code>

<code>    </code><code>private</code> <code>EditText etProductName; </code>

<code>    </code><code>private</code> <code>TextView tvResult; </code>

<code>    </code><code>class</code> <code>WSAsyncTask</code><code>extends</code> <code>AsyncTask </code>

<code>        </code><code>String result =</code><code>""</code><code>; </code>

<code>        </code><code>@Override</code> 

<code>        </code><code>protected</code> <code>Object doInBackground(Object... params) </code>

<code>            </code><code>try</code> 

<code>                </code><code>String serviceUrl =</code><code>"http://192.168.17.156:8080/axis2/services/SearchProductService?wsdl"</code><code>; </code>

<code>                </code><code>String methodName =</code><code>"getProduct"</code><code>; </code>

<code>                </code><code>SoapObject request =</code><code>new</code> <code>SoapObject(</code><code>"http://service"</code><code>, </code>

<code>                        </code><code>methodName); </code>

<code>                </code><code>request.addProperty(</code><code>"productName"</code><code>, etProductName.getText().toString()); </code>

<code>                </code><code>SoapSerializationEnvelope envelope =</code><code>new</code> <code>SoapSerializationEnvelope( </code>

<code>                        </code><code>SoapEnvelope.VER11); </code>

<code>                </code><code>envelope.bodyOut = request; </code>

<code>                </code><code>HttpTransportSE ht =</code><code>new</code> <code>HttpTransportSE(serviceUrl); </code>

<code>                </code><code>ht.call(</code><code>null</code><code>, envelope); </code>

<code>                </code><code>if</code> <code>(envelope.getResponse() !=</code><code>null</code><code>) </code>

<code>                </code><code>{ </code>

<code>                    </code><code>SoapObject soapObject = (SoapObject) envelope.getResponse(); </code>

<code>                    </code><code>result =</code><code>"产品名称:"</code> <code>+ soapObject.getProperty(</code><code>"name"</code><code>) +</code><code>"\n"</code><code>; </code>

<code>                    </code><code>result +=</code><code>"产品数量:"</code> <code>+ soapObject.getProperty(</code><code>"productNumber"</code><code>) </code>

<code>                            </code><code>+</code><code>"\n"</code><code>; </code>

<code>                    </code><code>result +=</code><code>"产品价格:"</code> <code>+ soapObject.getProperty(</code><code>"price"</code><code>); </code>

<code>                </code><code>} </code>

<code>                </code><code>else</code> 

<code>                    </code><code>result =</code><code>"无此产品."</code><code>; </code>

<code>            </code><code>catch</code> <code>(Exception e) </code>

<code>                </code><code>result =</code><code>"调用WebService错误."</code><code>; </code>

<code>            </code><code>// 必须使用post方法更新UI组件 </code>

<code>            </code><code>tvResult.post(</code><code>new</code> <code>Runnable() </code>

<code>                </code><code>@Override</code> 

<code>                </code><code>public</code> <code>void</code> <code>run() </code>

<code>                    </code><code>tvResult.setText(result); </code>

<code>            </code><code>}); </code>

<code>68</code>

<code>            </code><code>return</code> <code>null</code><code>; </code>

<code>69</code>

<code>70</code>

<code>71</code>

<code>72</code>

<code>73</code>

<code>74</code>

<code>75</code>

<code>    </code><code>// 异步执行调用WebService的任务   </code>

<code>76</code>

<code>        </code><code>new</code> <code>WSAsyncTask().execute(); </code>

<code>77</code>

<code>78</code>

<code>79</code>

<code>80</code>

<code>81</code>

<code>82</code>

<code>83</code>

<code>84</code>

<code>85</code>

<code>        </code><code>etProductName = (EditText) findViewById(R.id.etProductName); </code>

<code>86</code>

<code>        </code><code>tvResult = (TextView) findViewById(R.id.tvResult); </code>

<code>87</code>

<code>88</code>

<code>89</code>

     调用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组件阻塞。

继续阅读