当前位置:操作系统 > 安卓/Android >>

Android平台调用WebService详解

下面将通过一个示例讲解如何在Android平台调用Web Service。既然要调用Web Service,那就要先有Web Service。我们还是选择使用上篇文章中介绍的查询手机号码归属地的Web service,
1)新建Android工程,引入上面下载的ksoap2-android类库
      Android工程的创建就不多说了,主要想说明的是如何向Android工程中添加第三方jar包。当然,添加第3方jar的方式有多种,我个人比较喜欢用下面这种方式,即先将第三方jar包拷贝到工程某个目录下,再将其加入到工程的Build Path中。
      例如,我创建的Android工程名为WSClient,在工程名上点击右键,新建一个Folder(目录或文件夹),名为libs,然后将ksoap2-android类库拷贝到libs目录中,如下图所示:
\
            
      接着,在jar包ksoap2-Android-assembly-2.4-jar-with-dependencies.jar上点击右键,依次选择“Build Path”-“Add to Build Path”。再在工程名上点击右键,依次选择“Build Path”-“Config Build Path...”,将看到如下所示界面:
   \  
选中ksoap2 jar包前面的选项框,点击OK,则完成了ksoap2 jar包的添加(说明:在Android工程中,添加其它jar包的方法完全一样,操作一两遍后,你会发现其实很简单的)。

2)编写布局文件res/layout/main.xml    
 
 
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:paddingTop="5dip"    android:paddingLeft="5dip"    android:paddingRight="5dip"    >    <TextView    android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="手机号码(段):"    />    <EditText android:id="@+id/phone_sec"        android:layout_width="fill_parent"      android:layout_height="wrap_content"        android:inputType="textPhonetic"        android:singleLine="true"       android:hint="例如:1398547"    />    <Button android:id="@+id/query_btn"        android:layout_width="wrap_content"     android:layout_height="wrap_content"        android:layout_gravity="right"      android:text="查询"       /><TextView android:id="@+id/result_text"    android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:layout_gravity="center_horizontal|center_vertical"    /></LinearLayout> 
3)编写MainActivity类     
 
package com.liufeng.ws.activity;import org.ksoap2.SoapEnvelope;import org.ksoap2.serialization.SoapObject;import org.ksoap2.serialization.SoapSerializationEnvelope;import org.ksoap2.transport.HttpTransportSE;import Android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;/** * Android平台调用WebService(手机号码归属地查询) *  * @author liufeng * @date 2011-05-18 */public class MainActivity extends Activity {private EditText phoneSecEditText;private TextView resultView;private Button queryButton;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);phoneSecEditText = (EditText) findViewById(R.id.phone_sec);resultView = (TextView) findViewById(R.id.result_text);queryButton = (Button) findViewById(R.id.query_btn);queryButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 手机号码(段)String phoneSec = phoneSecEditText.getText().toString().trim();// 简单判断用户输入的手机号码(段)是否合法if ("".equals(phoneSec) || phoneSec.length() < 7) {// 给出错误提示phoneSecEditText.setError("您输入的手机号码(段)有误!");phoneSecEditText.requestFocus();// 将显示查询结果的TextView清空resultView.setText("");return;}// 查询手机号码(段)信息getRemoteInfo(phoneSec);}});}/** * 手机号段归属地查询 *  * @param phoneSec 手机号段 */public void getRemoteInfo(String phoneSec) {// 命名空间String nameSpace = "http://WebXml.com.cn/";// 调用的方法名称String methodName = "getMobileCodeInfo";// EndPointString endPoint = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";// SOAP ActionString soapAction = "http://WebXml.com.cn/getMobileCodeInfo";// 指定WebService的命名空间和调用的方法名SoapObject rpc = new SoapObject(nameSpace, methodName);// 设置需调用WebService接口需要传入的两个参数mobileCode、userIdrpc.addProperty("mobileCode", phoneSec);rpc.addProperty("userId", "");// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);envelope.bodyOut = rpc;// 设置是否调用的是dotNet开发的WebServiceenvelope.dotNet = true;// 等价于envelope.bodyOut = rpc;envelope.setOutputSoapObject(rpc);HttpTransportSE transport = new HttpTransportSE(endPoint);try {// 调用WebServicetransport.call(soapAction, envelope);} catch (Exception e) {e.printStackTrace();}// 获取返回的数据SoapObject object = (SoapObject) envelope.bodyIn;// 获取返回的结果String result = object.getProperty("getMobileCodeInfoResult").toString();// 将WebService返回的结果显示在TextView中resultView.setText(result);}} 
讲解:
      注意点1:如代码中的62-69行所示,调用Web Service之前你需要先弄清楚这4个的值分别是什么:命名空间、调用的方法名称、EndPoint和SOAP Action。当在浏览器中访问WSDL时,很容易得知命名空间、调用的方法名称是什么(不明白的请看上篇文章),至于EndPoint通常是将WSDL地址末尾的"?wsdl"去除后剩余的部分;而SOAP Action通常为命名空间 + 调用的方法名称。
      注意点2:75-76行是设置调用WebService接口方法需要传入的参数。(在WSDL中能够看到调用方法需要传入的参数个数及参数名称,在设置参数时最好指明每一个传入参数的名称,如本例中的mobileCode、userId。网上有些资料说在需要传入多个参数时,只要多个参数的顺序与WSDL中参数出现的顺序一致即可,名称并不需要和WSDL中的一致,但实际测试发现,大多数情况下并不可行!)
      例如下面图版上显示的WSDL片段,调用该Web Service的checkUserInfo方法就需要传入4个参数,参数名称分别为:in0、in1、in2和in3。
\
           
      注意点3:也许你会对第100行代码产生疑惑,为什么要用object.getProperty("getMobileCodeInfoResult")来取得调用结果?那是因为WSDL中明确告诉了返回结果是String数组,它的名称为getDatabaseInfoResult,WSDL中的描述如下:
            <s:element minOccurs="0" maxOccu

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,