在android中如何 调用webservice

来源:互联网 发布:饮食养生的软件 编辑:程序博客网 时间:2024/05/16 12:54

Android端与服务器交互 一般情况下,我们可以使用SOCKET,HTTP(GET,POST)等,我们也可以使用另外一种方式,webservice,

它是一种基于SAOP协议的远程调用标准,通过webservice可以将不同操作系统平台,不同语言,不同技术整合到一起。说白了就是一种中间件技术.

我们在android客户端中,有时需要一些库,比如XFire,Axis2,CXF等等来支持访问WebService,由于android sdk等并没有提供这些库,所以并不适合我们资源有限的android手机客户端,这里有KSOAP这个第三方的类库,可以帮助我们获取服务器端webService调用,KSOAP已经提供了基于android版本的jar包.

先下载KSOAP包:ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar包 

然后新建一个android项目:并把下载的KSOAP包放在android项目的lib目录下:右键->build path->configure build path--选择Libraries,如图:

以下分为七个步骤来调用WebService方法:

第一:实例化SoapObject 对象,指定webService的命名空间(从相关WSDL文档中可以查看命名空间),以及调用方法名称。

public final static String NAMESPACE = "http://tempuri.org/";

public static String wsdl ="http://XXsoft.com/Service1.asmx";

private final static String defaultAddress ="XXsoft.com";
 private final static String defaultPage = "service1.asmx";
 public final static String CONFIG_PATH = "/data/data/org.DigitalCM/DigitalCMWebserviceConfig.dat";

第二步:假设方法有参数的话,设置调用方法参数

request.addProperty("参数名称","参数值");

第三步:设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致):

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
    SoapEnvelope.VER10);
  envelope.setOutputSoapObject(request);

  // envelope.bodyOut = request;

第四步:构建传输对象,并指明WSDL文档URL:

HttpTransportSE ht = new HttpTransportSE(wsdl);

第五步:调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象):

ht.call(SOAP_ACTION, envelope);// 调用webservice(其中参数一SOAP_ACTION为命名空间+方法名,参数二为envelope)

第六步:解析返回数据:

resultObject = envelope.getResponse();// 第7步:使用getResponse方法获得WebService方法的返回结果

 

 

原理和步骤过程了解后,我们下面结合具体项目实例给大家分享下,我们还是以之前的一篇文章: 登陆界面软件自动更新功能的实现http://blog.csdn.net/jindegegesun/article/details/7232779

为例进行,简化更改一个登陆过程。

1、新建一个登陆的布局界面

[html] view plain copy print?
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     android:layout_width="fill_parent"    
  4.     android:layout_height="fill_parent"    
  5.     android:background="@drawable/main_bg"    
  6.     android:orientation="vertical" >    
  7.     
  8.     <ScrollView    
  9.         android:id="@+id/Main_LinearLayout"    
  10.         android:layout_width="fill_parent"    
  11.         android:layout_height="wrap_content"    
  12.         android:layout_above="@+id/bottommenu"    
  13.         android:layout_alignParentTop="true" >    
  14.     
  15.         <LinearLayout    
  16.             android:id="@+id/Main_LinearLayout"    
  17.             android:layout_width="fill_parent"    
  18.             android:layout_height="fill_parent"    
  19.             android:orientation="vertical" >    
  20.     
  21.             <ImageView    
  22.                 android:id="@+id/TitleBG"    
  23.                 android:layout_width="fill_parent"    
  24.                 android:layout_height="wrap_content"    
  25.                 android:background="@drawable/title_bg" >    
  26.             </ImageView>    
  27.     
  28.             <TextView    
  29.                 android:id="@+id/system_name"    
  30.                 android:layout_width="fill_parent"    
  31.                 android:layout_height="wrap_content"    
  32.                 android:gravity="center"    
  33.                 android:paddingTop="20dip"    
  34.                 android:text="@string/login_name"    
  35.                 android:textColor="@drawable/black"    
  36.                 android:textSize="30sp" >    
  37.             </TextView>    
  38.     
  39.             <TableLayout    
  40.                 android:id="@+id/TableLayout01"    
  41.                 android:layout_width="fill_parent"    
  42.                 android:layout_height="wrap_content"    
  43.                 android:paddingLeft="20dip"    
  44.                 android:paddingRight="20dip"    
  45.                 android:paddingTop="20dip"    
  46.                 android:shrinkColumns="1"    
  47.                 android:stretchColumns="1" >    
  48.     
  49.                 <TableRow android:paddingTop="15dip" >    
  50.     
  51.                     <TextView    
  52.                         android:id="@+id/TextView01"    
  53.                         android:padding="10dip"    
  54.                         android:text="@string/user_code_text"    
  55.                         android:textColor="@drawable/black"    
  56.                         android:textSize="18sp" >    
  57.                     </TextView>    
  58.     
  59.                     <EditText    
  60.                         android:id="@+id/user_code"    
  61.                         android:hint="@string/username_hint"    
  62.                         android:padding="10dip"    
  63.                         android:textSize="16sp" />    
  64.                 </TableRow>    
  65.     
  66.                 <TableRow android:paddingTop="15dip" >    
  67.     
  68.                     <TextView    
  69.                         android:id="@+id/TextView02"    
  70.                         android:padding="10dip"    
  71.                         android:text="@string/password_text"    
  72.                         android:textColor="@drawable/black"    
  73.                         android:textSize="18sp" >    
  74.                     </TextView>    
  75.     
  76.                     <EditText    
  77.                         android:id="@+id/user_pwd"    
  78.                         android:hint="@string/password_hint"    
  79.                         android:padding="10dip"    
  80.                         android:password="true"    
  81.                         android:textSize="16sp" />    
  82.                 </TableRow>    
  83.     
  84.                 <TableRow    
  85.                     android:gravity="center"    
  86.                     android:paddingTop="10dip" >    
  87.     
  88.                     <CheckBox    
  89.                         android:id="@+id/remember_pwd"    
  90.                         android:layout_width="wrap_content"    
  91.                         android:layout_height="wrap_content"    
  92.                         android:checked="true"    
  93.                         android:text="@string/rememberpwd_text"    
  94.                         android:textColor="@drawable/black" />    
  95.                 </TableRow>    
  96.             </TableLayout>    
  97.         </LinearLayout>    
  98.     </ScrollView>    
  99.     
  100.     <LinearLayout    
  101.         android:id="@id/bottommenu"    
  102.         android:layout_width="fill_parent"    
  103.         android:layout_height="wrap_content"    
  104.         android:layout_alignParentBottom="true"    
  105.         android:orientation="horizontal"    
  106.         android:padding="10dip" >    
  107.     
  108.         <Button    
  109.             android:id="@+id/login"    
  110.             android:layout_width="wrap_content"    
  111.             android:layout_height="wrap_content"    
  112.             android:layout_weight="1"    
  113.             android:text="@string/login_text" >    
  114.         </Button>    
  115.     
  116.         <Button    
  117.             android:id="@+id/exit"    
  118.             android:layout_width="wrap_content"    
  119.             android:layout_height="wrap_content"    
  120.             android:layout_weight="1"    
  121.             android:text="@string/exit_text" >    
  122.         </Button>    
  123.     </LinearLayout>    
  124.     
  125. </RelativeLayout>    
第二步:建立登陆的Activity
[java] view plain copy print?
  1. package cn.jindegegesun.activity;  
  2. import java.util.HashMap;  
  3. import java.util.List;  
  4. import java.util.Map;  
  5. import java.util.Properties;  
  6.   
  7.   
  8. import org.DigitalCM.entities.UserInfo;  
  9. import org.ksoap2.serialization.SoapObject;  
  10.   
  11. import cn.jindegegesun.util.PropertyUtil;  
  12. import cn.jindegegesun.webservice.WSObjectMapUtil;  
  13. import cn.jindegegesun.webservice.WSObjectUtil;  
  14. import cn.jindegegesun.webservice.WSUtil;  
  15. import cn.jindegegesun.webservice.WebServiceConfig;  
  16. import android.app.AlertDialog;  
  17. import android.app.Dialog;  
  18. import android.app.ProgressDialog;  
  19. import android.app.SearchManager.OnCancelListener;  
  20. import android.app.SearchManager.OnDismissListener;  
  21. import android.content.DialogInterface;  
  22. import android.content.Intent;  
  23. import android.net.Uri;  
  24. import android.os.Bundle;  
  25. import android.os.Handler;  
  26. import android.os.Message;  
  27. import android.util.Log;  
  28. import android.view.View;  
  29. import android.view.View.OnClickListener;  
  30. import android.widget.Button;  
  31. import android.widget.CheckBox;  
  32. import android.widget.EditText;  
  33.   
  34. public class DigitalCity extends ContextActivity implements OnClickListener {  
  35.   
  36.     public final static int PROGRESS_DIALOG = 1;  
  37.     public final static int DIALOG_LOGIN_FAIELD = 2;  
  38.     public final static int DIALOG_CONNECT_ERROR = 3;  
  39.     public final static int DIALOG_USER_PWD_EMPTY = 4;  
  40.     public final static int DIALOG_EXIT_PROMPT = 5;  
  41.     public final static int DIALOG_VERSION_UPDATE = 6;  
  42.     private Button login = null;  
  43.     private Button exit = null;  
  44.     private EditText userCode = null;  
  45.     private EditText password = null;  
  46.     private CheckBox rememberpwd = null;  
  47.   
  48.   
  49.   
  50.     /** Called when the activity is first created. */  
  51.     @Override  
  52.     public void onCreate(Bundle savedInstanceState) {  
  53.         super.onCreate(savedInstanceState);  
  54.         setContentView(R.layout.login);  
  55.       
  56.         findViews();  
  57.         loadConfig();  
  58.         setOnClickListener();  
  59.   
  60.     }  
  61.   
  62.     @Override  
  63.     public void onClick(View v) {  
  64.         // TODO Auto-generated method stub  
  65.   
  66.     }  
  67.   
  68.     public void setOnClickListener() {  
  69.   
  70.         /* 为 Button 注册点击事件监听对象,采用了匿名内部类的方式。 */  
  71.         login.setOnClickListener(new View.OnClickListener() {  
  72.             @Override  
  73.             public void onClick(View v) {  
  74.               login();  
  75.                   
  76.             }  
  77.         }  
  78. );  
  79.   
  80.         /* 为 Button 注册点击事件监听对象,采用了匿名内部类的方式。 */  
  81.         exit.setOnClickListener(new View.OnClickListener() {  
  82.             @Override  
  83.             public void onClick(View v) {  
  84.                 exitApp();  
  85.             }  
  86.         });  
  87.     }  
  88.     public void findViews() {  
  89.         userCode = (EditText) findViewById(R.id.user_code);  
  90.         password = (EditText) findViewById(R.id.user_pwd);  
  91.         rememberpwd = (CheckBox)   
  92.                 findViewById(R.id.remember_pwd);  
  93.         login = (Button) findViewById(R.id.login);  
  94.         exit = (Button) findViewById(R.id.exit);  
  95.         // outlineLogin = (CheckBox)  
  96.         // contextActivity.findViewById(R.id.outline_login);  
  97.     }  
  98.   
  99.     @SuppressWarnings("static-access")  
  100.     public void login() {  
  101.           
  102.                 new Thread(){  
  103.                     public void run(){  
  104.                         if (!validate(userCode.getText().toString(), password.getText()  
  105.                                 .toString()));  
  106.                               
  107.   
  108.                         Map<String, Object> params = new HashMap<String, Object>();  
  109.                         params.put("userName", userCode.getText().toString().trim()  
  110.                                 .toLowerCase());  
  111.                         params.put("userPwd", password.getText().toString());  
  112.   
  113.                         SoapObject result = null;  
  114.                         try {  
  115.                             result = WSUtil.getSoapObjectByCallingWS(  
  116.                                     WebServiceConfig.NAMESPACE, "login", params,  
  117.                                     WebServiceConfig.wsdl);  
  118.                             //log("SSSSSSSSSSSS");  
  119.                         } catch (Exception ex) {  
  120.                             showDialog(DIALOG_CONNECT_ERROR);  
  121.                               
  122.                             Log.e("Exception", ex.getMessage());  
  123.                               
  124.                         }  
  125.   
  126.                         if (result == null) {  
  127.                             loginFailed();  
  128.                           
  129.                         }  
  130.   
  131.                         WSObjectUtil wsObjectUtil = new WSObjectUtil();  
  132.                         SoapObject dataSet = null;  
  133.                         try {  
  134.                             dataSet = wsObjectUtil.getDataSetObject(result);  
  135.                         } catch (Exception e) {  
  136.                             loginFailed();  
  137.                               
  138.                         }  
  139.   
  140.                         if (dataSet == null) {  
  141.                             loginFailed();  
  142.                               
  143.                         }  
  144.                         List<Map<String, Object>> rowMapList = WSObjectMapUtil  
  145.                                 .getRowMapList(dataSet);  
  146.   
  147.                         UserInfo.setUserInfo(rowMapList.get(0));  
  148.                         Intent intent =new Intent(DigitalCity.this,Main.class);  
  149.                         startActivity(intent);  
  150.                           
  151.                     }  
  152.                 }.start();  
  153.           
  154.                   
  155.           
  156.     }  
  157.   
  158.     private Boolean validate(String user_code, String password) {  
  159.         if (user_code == null || user_code.trim().equals("")  
  160.                 || password == null || password.trim().equals("")) {  
  161.             showDialog(DIALOG_USER_PWD_EMPTY);  
  162.             return false;  
  163.         }  
  164.   
  165.         return true;  
  166.     }  
  167.   
  168.     public void loadConfig() {  
  169.   
  170.         Properties properties = PropertyUtil  
  171.                 .loadConfig(WebServiceConfig.CONFIG_PATH);  
  172.         String username = properties.getProperty("username");  
  173.         String pwd = properties.getProperty("password");  
  174.   
  175.         properties = PropertyUtil.loadConfig(WebServiceConfig.CONFIG_PATH);  
  176.         username = properties.getProperty("username");  
  177.         pwd = properties.getProperty("password");  
  178.   
  179.         if (pwd != null && !pwd.equals("")) {  
  180.             rememberpwd.setChecked(true);  
  181.             password.setText(pwd);  
  182.         } else {  
  183.             rememberpwd.setChecked(false);  
  184.         }  
  185.   
  186.         userCode.setText(username);  
  187.     }  
  188.   
  189.     private void loginFailed() {  
  190.     showDialog(DIALOG_LOGIN_FAIELD);  
  191.     }  
  192.   
  193.     private void exitApp() {  
  194.         showDialog(DIALOG_EXIT_PROMPT);  
  195.     }  
  196.   
  197.     @Override  
  198.     protected Dialog onCreateDialog(int id) {  
  199.         // TODO Auto-generated method stub  
  200.         switch(id){  
  201.         case LoginActions.DIALOG_LOGIN_FAIELD:  
  202.             return new AlertDialog.Builder(this)  
  203.                     .setTitle(R.string.error_title)  
  204.                     .setMessage(R.string.login_failed)  
  205.                     .setPositiveButton(R.string.OK_text,  
  206.                             new DialogInterface.OnClickListener() {  
  207.   
  208.                                 @Override  
  209.                                 public void onClick(DialogInterface dialog,  
  210.                                         int arg1) {  
  211.                                     // TODO Auto-generated method stub  
  212.                                     dialog.cancel();  
  213.                                 }  
  214.                             }).show();  
  215.         case LoginActions.DIALOG_CONNECT_ERROR:  
  216.             return new AlertDialog.Builder(this)  
  217.                     .setTitle(R.string.message_title)  
  218.                     .setMessage(R.string.connection_error)  
  219.                     .setPositiveButton(R.string.OK_text,  
  220.                             new DialogInterface.OnClickListener() {  
  221.   
  222.                                 @Override  
  223.                                 public void onClick(DialogInterface dialog,  
  224.                                         int which) {  
  225.                                     // TODO Auto-generated method stub  
  226.                                     dialog.cancel();  
  227.                                 }  
  228.   
  229.                             }).show();  
  230.         case LoginActions.DIALOG_USER_PWD_EMPTY:  
  231.             return new AlertDialog.Builder(this)  
  232.                     .setTitle(R.string.message_title)  
  233.                     .setMessage(R.string.usercode_or_password_empty_warning)  
  234.                     .setPositiveButton(R.string.OK_text,  
  235.                             new DialogInterface.OnClickListener() {  
  236.   
  237.                                 @Override  
  238.                                 public void onClick(DialogInterface dialog,  
  239.                                         int which) {  
  240.                                     // TODO Auto-generated method stub  
  241.                                     dialog.cancel();  
  242.                                 }  
  243.   
  244.                             }).show();  
  245.         case LoginActions.DIALOG_EXIT_PROMPT:  
  246.             return new AlertDialog.Builder(this)  
  247.                     .setTitle(R.string.message_title)  
  248.                     .setMessage(R.string.exit_prompt)  
  249.                     .setPositiveButton(R.string.OK_text,  
  250.                             new DialogInterface.OnClickListener() {  
  251.                                 public void onClick(DialogInterface dialog,  
  252.                                         int which) {  
  253.                                     finish();  
  254.                                 }  
  255.                             })  
  256.                     .setNegativeButton(R.string.cancel_text,  
  257.                             new DialogInterface.OnClickListener() {  
  258.                                 public void onClick(DialogInterface dialog,  
  259.                                         int which) {  
  260.                                     dialog.cancel();  
  261.                                 }  
  262.                             }).show();  
  263.         }  
  264.         return super.onCreateDialog(id);  
  265.     }  
  266.       
  267.   


第三步:新建一个登陆进入后的布局文件main.xml以及Main.Activity,这个类和界面都很简单
[html] view plain copy print?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.     <TextView android:layout_width="fill_parent"  
  7.               android:layout_height="fill_parent"  
  8.               android:text="hello,jindegege!"/>"  
  9.       
  10.   
  11. </LinearLayout>  


 

 

 

 

[java] view plain copy print?
  1. package cn.jindegegesun.activity;  
  2.   
  3.   
  4. import android.app.Activity;  
  5. import android.os.Bundle;  
  6. import android.view.Window;  
  7.   
  8.   
  9.   
  10.   
  11.   
  12. public class Main extends Activity {  
  13.   
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         requestWindowFeature(Window.FEATURE_NO_TITLE);//设置全屏  
  17.         setContentView(R.layout.main);  
  18.   
  19.           
  20.   
  21.   
  22.     }  
  23. }  



第四步:添加程序所用的权限:

[html] view plain copy print?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="cn.jindegegesun.activity"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk android:minSdkVersion="7" />  
  8.   
  9.     <application  
  10.         android:icon="@drawable/ic_launcher"  
  11.         android:label="@string/app_name" >  
  12.         <activity  
  13.             android:name=".DigitalCity"  
  14.             android:label="@string/app_name" >  
  15.             <intent-filter>  
  16.                 <action android:name="android.intent.action.MAIN" />  
  17.   
  18.                 <category android:name="android.intent.category.LAUNCHER" />  
  19.             </intent-filter>  
  20.         </activity>  
  21.          <activity  
  22.             android:label="@string/login_name"  
  23.             android:name="cn.jindegegesun.activity.Main" >  
  24.         </activity>  
  25.     </application>  
  26.     <uses-permission android:name="android.permission.INTERNET" />  
  27. </manifest>  


注意:在第一个DigitalCity .activity的login()方法调用了webservice返回的数据,先贴出代码;

[java] view plain copy print?
  1. package cn.jindegegesun.webservice;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.HashMap;  
  6. import java.util.Iterator;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9. import java.util.Vector;  
  10.   
  11. import org.kobjects.base64.Base64;  
  12. import org.ksoap2.SoapEnvelope;  
  13. import org.ksoap2.SoapFault;  
  14. import org.ksoap2.serialization.PropertyInfo;  
  15. import org.ksoap2.serialization.SoapObject;  
  16. import org.ksoap2.serialization.SoapPrimitive;  
  17. import org.ksoap2.serialization.SoapSerializationEnvelope;  
  18. import org.ksoap2.transport.HttpTransportSE;  
  19. import org.xmlpull.v1.XmlPullParserException;  
  20.   
  21. import android.app.Activity;  
  22. import android.util.Log;  
  23.   
  24. public class WSUtil {  
  25.     public static Boolean getBooleanByCallingWS(String nameSpace,  
  26.             String methodName, Map<String, Object> params, String wsdl)  
  27.             throws IOException, XmlPullParserException {  
  28.         return (Boolean) getObjectByCallingWS(nameSpace, methodName, params,  
  29.                 wsdl);  
  30.     }  
  31.   
  32.     @SuppressWarnings("unchecked")  
  33.     public static Vector<SoapObject> getSoapObjectVectorByCallingWS(  
  34.             String nameSpace, String methodName, Map<String, Object> params,  
  35.             String wsdl) throws IOException, XmlPullParserException {  
  36.         return (Vector<SoapObject>) getObjectByCallingWS(nameSpace, methodName,  
  37.                 params, wsdl);  
  38.     }  
  39.   
  40.     public static SoapObject getSoapObjectByCallingWS(String nameSpace,  
  41.             String methodName, Map<String, Object> params, String wsdl)  
  42.             throws IOException, XmlPullParserException {  
  43.         return (SoapObject) getObjectByCallingWS(nameSpace, methodName, params,  
  44.                 wsdl);  
  45.     }  
  46.   
  47.     public static SoapPrimitive getSoapPrimitiveByCallingWS(String nameSpace,  
  48.             String methodName, Map<String, Object> params, String wsdl)  
  49.             throws IOException, XmlPullParserException {  
  50.         return (SoapPrimitive) getObjectByCallingWS(nameSpace, methodName,  
  51.                 params, wsdl);  
  52.     }  
  53.   
  54.     public static Object getObjectByCallingWS(String nameSpace,  
  55.             String methodName, Map<String, Object> params, String wsdl)  
  56.             throws IOException, XmlPullParserException {  
  57.   
  58.         final String SOAP_ACTION = nameSpace + methodName;  
  59.         Object soapPrimitiveResult = null;  
  60.   
  61.         SoapSerializationEnvelope envelope = constructRequestObject2(nameSpace,  
  62.                 methodName, params);  
  63.         soapPrimitiveResult = callWebservice(SOAP_ACTION, wsdl, envelope);  
  64.   
  65.         return soapPrimitiveResult;  
  66.     }  
  67.   
  68.     private static SoapSerializationEnvelope constructRequestObject2(  
  69.             String nameSpace, String methodName, Map<String, Object> params) {  
  70.         <span style="color:#ff0000;">SoapObject request = new SoapObject(nameSpace, methodName);// 第一步,实例化SoapObject对象,并指定命名空间和方法名  
  71. </span>     if (params != null && !params.isEmpty()) {  
  72.             for (Iterator<Map.Entry<String, Object>> it = params.entrySet()  
  73.                     .iterator(); it.hasNext();) {  
  74.                 Map.Entry<String, Object> e = it.next();  
  75.                 if (e.getValue() instanceof byte[]) {  
  76.                     byte[] d = (byte[]) e.getValue();  
  77.                     String data = new String(Base64.encode(d));  
  78.                     // request.addProperty(e.getKey(), new  
  79.                     // SoapPrimitive(SoapEnvelope.ENC, "base64Binary", data));  
  80.                     <span style="color:#ff0000;">request.addProperty(e.getKey(), data);// 第二步,设置调用参数方法,包括参数名称和参数值  
  81. </span>             } else {  
  82.                     request.addProperty(e.getKey().toString(), e.getValue());  
  83.                 }  
  84.             }  
  85.         }  
  86.         <span style="color:#ff0000;">// 第三步,设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用到的WEBSERVICE中的版本号一致)  
  87.         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
  88.                 SoapEnvelope.VER10);  
  89.         envelope.setOutputSoapObject(request);  
  90.   
  91. </span>     // envelope.bodyOut = request;  
  92.         envelope.dotNet = true;  
  93.         envelope.encodingStyle = SoapSerializationEnvelope.ENC;  
  94.         return envelope;  
  95.     }  
  96.   
  97.     public static SoapPrimitive getSoapPrimitiveByCallingWSWithFile(  
  98.             String nameSpace, String methodName, Map<String, Object> params,  
  99.             String wsdl) throws IOException, XmlPullParserException {  
  100.   
  101.         final String SOAP_ACTION = nameSpace + methodName;  
  102.         SoapPrimitive soapPrimitiveResult = null;  
  103.   
  104.         SoapObject request = constructRequestObjectWithFile(nameSpace,  
  105.                 methodName, params);  
  106.         SoapSerializationEnvelope envelope = getEncEnvelope(request);  
  107.         soapPrimitiveResult = (SoapPrimitive) callWebservice(SOAP_ACTION, wsdl,  
  108.                 envelope);  
  109.   
  110.         return soapPrimitiveResult;  
  111.     }  
  112.   
  113.     public static Object callWebservice(String SOAP_ACTION, String wsdl,  
  114.             SoapSerializationEnvelope envelope) throws IOException,  
  115.             XmlPullParserException {  
  116.   
  117.         // registerObjects(envelope);  
  118.         Object resultObject = null;  
  119.         <span style="color:#ff0000;">HttpTransportSE ht = new HttpTransportSE(wsdl); // 第四步,构建传输对象,并指明wsdl文档url  
  120. </span>     try {  
  121.             <span style="color:#ff0000;">ht.call(SOAP_ACTION, envelope);// 第五步,调用webservice(其中参数一SOAP_ACTION为命名空间+方法名,参数二为envelope)  
  122.   
  123. </span>     } catch (IOException e) {  
  124.             Log.e("IOException:", e.getMessage());  
  125.             // androidHT.reset();  
  126.             throw e;  
  127.         } catch (XmlPullParserException e1) {  
  128.             Log.e("XmlPullParserException", e1.getMessage());  
  129.             throw e1;  
  130.         }  
  131.         try {  
  132.             <span style="color:#ff0000;">resultObject = envelope.getResponse();// 第6步:使用getResponse方法获得WebService方法的返回结果  
  133. </span>     } catch (SoapFault e) {  
  134.             Log.e("SoapFault", e.getMessage());  
  135.         }  
  136.         return resultObject;  
  137.     }  
  138.   
  139.     public static SoapObject constructRequestObject(String nameSpace,  
  140.             String methodName, Map<String, Object> params) {  
  141.   
  142.         SoapObject request = new SoapObject(nameSpace, methodName);  
  143.   
  144.         if (params != null && !params.isEmpty()) {  
  145.             for (Iterator<Map.Entry<String, Object>> it = params.entrySet()  
  146.                     .iterator(); it.hasNext();) {  
  147.                 Map.Entry<String, Object> e = it.next();  
  148.                 request.addProperty(e.getKey().toString(), e.getValue());  
  149.             }  
  150.         }  
  151.         return request;  
  152.     }  
  153.   
  154.     public static SoapObject constructRequestObjectWithFile(String nameSpace,  
  155.             String methodName, Map<String, Object> params) {  
  156.   
  157.         SoapObject request = new SoapObject(nameSpace, methodName);  
  158.         if (params != null && !params.isEmpty()) {  
  159.             for (Iterator<Map.Entry<String, Object>> it = params.entrySet()  
  160.                     .iterator(); it.hasNext();) {  
  161.                 Map.Entry<String, Object> e = it.next();  
  162.                 if (e.getValue() instanceof byte[]) {  
  163.                     byte[] d = (byte[]) e.getValue();  
  164.                     String data = new String(Base64.encode(d));  
  165.                     request.addProperty(e.getKey(), new SoapPrimitive(  
  166.                             SoapEnvelope.ENC, "base64Binary", data));  
  167.                 } else {  
  168.                     request.addProperty(e.getKey().toString(), e.getValue());  
  169.                 }  
  170.             }  
  171.         }  
  172.         return request;  
  173.     }  
  174.   
  175.     public static SoapSerializationEnvelope getEncEnvelope(SoapObject request) {  
  176.   
  177.         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
  178.                 SoapEnvelope.VER11);  
  179.         envelope.setOutputSoapObject(request);  
  180.   
  181.         // envelope.bodyOut = request;  
  182.         envelope.dotNet = true;  
  183.         envelope.encodingStyle = SoapSerializationEnvelope.ENC;  
  184.         return envelope;  
  185.     }  
  186.   
  187.     public static SoapSerializationEnvelope getEnvelope(SoapObject request) {  
  188.   
  189.         // SoapSerializationEnvelope envelope=new  
  190.         // SoapSerializationEnvelope(SoapEnvelope.VER10);//SOAP 1.0  
  191.         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
  192.                 SoapEnvelope.VER10);// SOAP 1.1  
  193.         // SoapSerializationEnvelope envelope=new  
  194.         // SoapSerializationEnvelope(SoapEnvelope.VER12);//SOAP 1.2  
  195.   
  196.         envelope.dotNet = true;  
  197.         // envelope.bodyOut = request;  
  198.         envelope.setOutputSoapObject(request);  
  199.   
  200.         return envelope;  
  201.     }  
  202.   
  203.     public static Map<String, String> getDatabyWebservicesMap(  
  204.             Activity activity, HashMap<String, Object> params, String servies) {  
  205.   
  206.         SoapObject queryResult = null;  
  207.         ArrayList<List<String>> rows = null;  
  208.   
  209.         try {  
  210.             queryResult = WSUtil.getSoapObjectByCallingWS(  
  211.                     WebServiceConfig.NAMESPACE, servies, params,  
  212.                     WebServiceConfig.wsdl);  
  213.         } catch (Exception e) {  
  214.             /* 
  215.              * new 
  216.              * AlertDialog.Builder(activity.getApplicationContext()).setTitle 
  217.              * (R.string.message_title) .setMessage(R.string.connection_error) 
  218.              * .setPositiveButton(R.string.OK_text, null).show(); 
  219.              * activity.finish(); 
  220.              */  
  221.             // return;  
  222.         }  
  223.   
  224.         return WSUtil.handleResultMap(queryResult);  
  225.     }  
  226.   
  227.     public static Map<String, String> handleResultMap(SoapObject queryResult) {  
  228.         WSObjectUtil wsObjectUtil = new WSObjectUtil();  
  229.         SoapObject dataset = WSUtil.getDataRow(queryResult, 0);  
  230.   
  231.         if (dataset == null) {  
  232.             // noResult();  
  233.             return null;  
  234.         }  
  235.         return (Map<String, String>) WSUtil.getPropertiesMap(dataset);  
  236.     }  
  237.   
  238.     public static SoapObject getDataRow(SoapObject o, Integer index) {  
  239.         SoapObject row = null;  
  240.   
  241.         try {  
  242.             SoapObject diffgram = (SoapObject) o.getProperty(1);  
  243.             SoapObject rows = (SoapObject) diffgram.getProperty(0);  
  244.             row = (SoapObject) rows.getProperty(index);  
  245.         } catch (Exception e) {  
  246.             Log.e("Exception", e.getMessage());  
  247.         }  
  248.         return row;  
  249.     }  
  250.   
  251.     public static Map<String, String> getPropertiesMap(SoapObject o) {  
  252.         Map<String, String> propertiesMap = new HashMap<String, String>();  
  253.   
  254.         for (int i = 0; i < o.getPropertyCount(); i++) {  
  255.             PropertyInfo propertyInfo = new PropertyInfo();  
  256.             o.getPropertyInfo(i, propertyInfo);  
  257.             String propertyName = propertyInfo.getName();  
  258.             propertiesMap.put(propertyName, o.getProperty(i).toString());  
  259.         }  
  260.   
  261.         return propertiesMap;  
  262.     }  
  263.   
  264.     public static ArrayList<List<String>> handleResult(SoapObject queryResult) {  
  265.         WSObjectUtil wsObjectUtil = new WSObjectUtil();  
  266.         SoapObject dataset = wsObjectUtil.getDataTableObject(queryResult);  
  267.   
  268.         if (dataset == null) {  
  269.             // noResult();  
  270.             return null;  
  271.         }  
  272.         ArrayList<List<String>> rowparameter = new ArrayList<List<String>>();  
  273.         rowparameter = (ArrayList<List<String>>) WSUtil  
  274.                 .getPropertiesTableList(dataset);  
  275.         return rowparameter;  
  276.     }  
  277.   
  278.     public static List<List<String>> getPropertiesTableList(SoapObject o) {  
  279.         List<List<String>> propertiesTableList = new ArrayList<List<String>>();  
  280.   
  281.         try {  
  282.             for (int i = 0; i < o.getPropertyCount(); i++) {  
  283.                 propertiesTableList.add(getPropertiesList((SoapObject) o  
  284.                         .getProperty(i)));  
  285.             }  
  286.         } catch (Exception e) {  
  287.             Log.e("Exception", e.getMessage());  
  288.         }  
  289.   
  290.         return propertiesTableList;  
  291.     }  
  292.   
  293.     public static List<String> getPropertiesList(SoapObject o) {  
  294.         List<String> propertiesList = new ArrayList<String>();  
  295.   
  296.         try {  
  297.             for (int i = 0; i < o.getPropertyCount(); i++) {  
  298.                 propertiesList.add(o.getProperty(i).toString());  
  299.             }  
  300.         } catch (Exception e) {  
  301.             Log.e("Exception", e.getMessage());  
  302.         }  
  303.   
  304.         return propertiesList;  
  305.     }  

以上的红色字体部分就是具体调用webservice的具体步骤,最后一步,也就是第六步将会提供结果给调用webservice的方法,然后login()方法将通过
result = WSUtil.getSoapObjectByCallingWS(
         WebServiceConfig.NAMESPACE, "login", params,
         WebServiceConfig.wsdl);

得到第六步返回的结果。

当返回的结果与登陆界面输入的帐号和密码匹配后,登陆就成功了。

 

当然与服务器交互,这里还需要写接口,关键是其中的sql语句,我是在visual studio 2008上用c#写的一个login接口,如下:

[csharp] view plain copy print?
  1. [WebMethod(Description = "Android 接口: 登陆 userName 用户名 userPwd 用户密码")]  
  2.         public DataSet login(string userName, string userPwd)  
  3.         {  
  4.             DataSet ds = null;  
  5.   
  6.             string strSql = string.Format("select userid, username, password, deptid, realname, tel, email, usermemo, starttime, endtime, mapid, dwid, zw, deptname, purviewmid, dwmc from V_USERS t where t.username = '{0}' and t.password='{1}'", userName, userPwd);  
  7.             try  
  8.             {  
  9.                 RetStrSql(strSql);  
  10.                 ds = RetDataSet();  
  11.                 return ds;  
  12.             }  
  13.             catch (Exception ex)  
  14.             {  
  15.                 //throw new Exception(ex.Message);  
  16.                 return null;  
  17.   
  18.             }  
  19.         } 
好的,基本就是这样,贴上代码共享地址:http://download.csdn.net/detail/jindegegesun/4070721

0 0
原创粉丝点击