`

Android Call WebService

 
阅读更多
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://jinhesoft.com/Service1.asmx";

private final static String defaultAddress ="jinhesoft.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、新建一个登陆的布局界面
<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:background="@drawable/main_bg"  
    android:orientation="vertical" >  
  
    <ScrollView  
        android:id="@+id/Main_LinearLayout"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:layout_above="@+id/bottommenu"  
        android:layout_alignParentTop="true" >  
  
        <LinearLayout  
            android:id="@+id/Main_LinearLayout"  
            android:layout_width="fill_parent"  
            android:layout_height="fill_parent"  
            android:orientation="vertical" >  
  
            <ImageView  
                android:id="@+id/TitleBG"  
                android:layout_width="fill_parent"  
                android:layout_height="wrap_content"  
                android:background="@drawable/title_bg" >  
            </ImageView>  
  
            <TextView  
                android:id="@+id/system_name"  
                android:layout_width="fill_parent"  
                android:layout_height="wrap_content"  
                android:gravity="center"  
                android:paddingTop="20dip"  
                android:text="@string/login_name"  
                android:textColor="@drawable/black"  
                android:textSize="30sp" >  
            </TextView>  
  
            <TableLayout  
                android:id="@+id/TableLayout01"  
                android:layout_width="fill_parent"  
                android:layout_height="wrap_content"  
                android:paddingLeft="20dip"  
                android:paddingRight="20dip"  
                android:paddingTop="20dip"  
                android:shrinkColumns="1"  
                android:stretchColumns="1" >  
  
                <TableRow android:paddingTop="15dip" >  
  
                    <TextView  
                        android:id="@+id/TextView01"  
                        android:padding="10dip"  
                        android:text="@string/user_code_text"  
                        android:textColor="@drawable/black"  
                        android:textSize="18sp" >  
                    </TextView>  
  
                    <EditText  
                        android:id="@+id/user_code"  
                        android:hint="@string/username_hint"  
                        android:padding="10dip"  
                        android:textSize="16sp" />  
                </TableRow>  
  
                <TableRow android:paddingTop="15dip" >  
  
                    <TextView  
                        android:id="@+id/TextView02"  
                        android:padding="10dip"  
                        android:text="@string/password_text"  
                        android:textColor="@drawable/black"  
                        android:textSize="18sp" >  
                    </TextView>  
  
                    <EditText  
                        android:id="@+id/user_pwd"  
                        android:hint="@string/password_hint"  
                        android:padding="10dip"  
                        android:password="true"  
                        android:textSize="16sp" />  
                </TableRow>  
  
                <TableRow  
                    android:gravity="center"  
                    android:paddingTop="10dip" >  
  
                    <CheckBox  
                        android:id="@+id/remember_pwd"  
                        android:layout_width="wrap_content"  
                        android:layout_height="wrap_content"  
                        android:checked="true"  
                        android:text="@string/rememberpwd_text"  
                        android:textColor="@drawable/black" />  
                </TableRow>  
            </TableLayout>  
        </LinearLayout>  
    </ScrollView>  
  
    <LinearLayout  
        android:id="@id/bottommenu"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:layout_alignParentBottom="true"  
        android:orientation="horizontal"  
        android:padding="10dip" >  
  
        <Button  
            android:id="@+id/login"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_weight="1"  
            android:text="@string/login_text" >  
        </Button>  
  
        <Button  
            android:id="@+id/exit"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_weight="1"  
            android:text="@string/exit_text" >  
        </Button>  
    </LinearLayout>  
  
</RelativeLayout>  


第二步:建立登陆的Activity

package cn.jindegegesun.activity;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;


import org.DigitalCM.entities.UserInfo;
import org.ksoap2.serialization.SoapObject;

import cn.jindegegesun.util.PropertyUtil;
import cn.jindegegesun.webservice.WSObjectMapUtil;
import cn.jindegegesun.webservice.WSObjectUtil;
import cn.jindegegesun.webservice.WSUtil;
import cn.jindegegesun.webservice.WebServiceConfig;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.SearchManager.OnCancelListener;
import android.app.SearchManager.OnDismissListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class DigitalCity extends ContextActivity implements OnClickListener {

	public final static int PROGRESS_DIALOG = 1;
	public final static int DIALOG_LOGIN_FAIELD = 2;
	public final static int DIALOG_CONNECT_ERROR = 3;
	public final static int DIALOG_USER_PWD_EMPTY = 4;
	public final static int DIALOG_EXIT_PROMPT = 5;
	public final static int DIALOG_VERSION_UPDATE = 6;
	private Button login = null;
	private Button exit = null;
	private EditText userCode = null;
	private EditText password = null;
	private CheckBox rememberpwd = null;



	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
	
		findViews();
		loadConfig();
		setOnClickListener();

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	public void setOnClickListener() {

		/* 为 Button 注册点击事件监听对象,采用了匿名内部类的方式。 */
		login.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
			  login();
				
			}
		}
);

		/* 为 Button 注册点击事件监听对象,采用了匿名内部类的方式。 */
		exit.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				exitApp();
			}
		});
	}
	public void findViews() {
		userCode = (EditText) findViewById(R.id.user_code);
		password = (EditText) findViewById(R.id.user_pwd);
		rememberpwd = (CheckBox) 
				findViewById(R.id.remember_pwd);
		login = (Button) findViewById(R.id.login);
		exit = (Button) findViewById(R.id.exit);
		// outlineLogin = (CheckBox)
		// contextActivity.findViewById(R.id.outline_login);
	}

	@SuppressWarnings("static-access")
	public void login() {
		
		        new Thread(){
		        	public void run(){
		        		if (!validate(userCode.getText().toString(), password.getText()
								.toString()));
							

						Map<String, Object> params = new HashMap<String, Object>();
						params.put("userName", userCode.getText().toString().trim()
								.toLowerCase());
						params.put("userPwd", password.getText().toString());

						SoapObject result = null;
						try {
							result = WSUtil.getSoapObjectByCallingWS(
									WebServiceConfig.NAMESPACE, "login", params,
									WebServiceConfig.wsdl);
							//log("SSSSSSSSSSSS");
						} catch (Exception ex) {
							showDialog(DIALOG_CONNECT_ERROR);
							
							Log.e("Exception", ex.getMessage());
							
						}

						if (result == null) {
							loginFailed();
						
						}

						WSObjectUtil wsObjectUtil = new WSObjectUtil();
						SoapObject dataSet = null;
						try {
							dataSet = wsObjectUtil.getDataSetObject(result);
						} catch (Exception e) {
							loginFailed();
							
						}

						if (dataSet == null) {
							loginFailed();
							
						}
						List<Map<String, Object>> rowMapList = WSObjectMapUtil
								.getRowMapList(dataSet);

						UserInfo.setUserInfo(rowMapList.get(0));
						Intent intent =new Intent(DigitalCity.this,Main.class);
					    startActivity(intent);
						
		        	}
		        }.start();
		
				
		
	}

	private Boolean validate(String user_code, String password) {
		if (user_code == null || user_code.trim().equals("")
				|| password == null || password.trim().equals("")) {
			showDialog(DIALOG_USER_PWD_EMPTY);
			return false;
		}

		return true;
	}

	public void loadConfig() {

		Properties properties = PropertyUtil
				.loadConfig(WebServiceConfig.CONFIG_PATH);
		String username = properties.getProperty("username");
		String pwd = properties.getProperty("password");

		properties = PropertyUtil.loadConfig(WebServiceConfig.CONFIG_PATH);
		username = properties.getProperty("username");
		pwd = properties.getProperty("password");

		if (pwd != null && !pwd.equals("")) {
			rememberpwd.setChecked(true);
			password.setText(pwd);
		} else {
			rememberpwd.setChecked(false);
		}

		userCode.setText(username);
	}

	private void loginFailed() {
	showDialog(DIALOG_LOGIN_FAIELD);
	}

	private void exitApp() {
		showDialog(DIALOG_EXIT_PROMPT);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch(id){
		case LoginActions.DIALOG_LOGIN_FAIELD:
			return new AlertDialog.Builder(this)
					.setTitle(R.string.error_title)
					.setMessage(R.string.login_failed)
					.setPositiveButton(R.string.OK_text,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int arg1) {
									// TODO Auto-generated method stub
									dialog.cancel();
								}
							}).show();
		case LoginActions.DIALOG_CONNECT_ERROR:
			return new AlertDialog.Builder(this)
					.setTitle(R.string.message_title)
					.setMessage(R.string.connection_error)
					.setPositiveButton(R.string.OK_text,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.cancel();
								}

							}).show();
		case LoginActions.DIALOG_USER_PWD_EMPTY:
			return new AlertDialog.Builder(this)
					.setTitle(R.string.message_title)
					.setMessage(R.string.usercode_or_password_empty_warning)
					.setPositiveButton(R.string.OK_text,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									dialog.cancel();
								}

							}).show();
		case LoginActions.DIALOG_EXIT_PROMPT:
			return new AlertDialog.Builder(this)
					.setTitle(R.string.message_title)
					.setMessage(R.string.exit_prompt)
					.setPositiveButton(R.string.OK_text,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							})
					.setNegativeButton(R.string.cancel_text,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							}).show();
		}
		return super.onCreateDialog(id);
	}
	

}


package cn.jindegegesun.activity;


import android.app.Activity;
import android.os.Bundle;
import android.view.Window;





public class Main extends Activity {

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);//设置全屏
		setContentView(R.layout.main);

		


	}
}


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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.jindegegesun.activity"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="7" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".DigitalCity"
            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:label="@string/login_name"
            android:name="cn.jindegegesun.activity.Main" >
        </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>


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

package cn.jindegegesun.webservice;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.kobjects.base64.Base64;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.util.Log;

public class WSUtil {
	public static Boolean getBooleanByCallingWS(String nameSpace,
			String methodName, Map<String, Object> params, String wsdl)
			throws IOException, XmlPullParserException {
		return (Boolean) getObjectByCallingWS(nameSpace, methodName, params,
				wsdl);
	}

	@SuppressWarnings("unchecked")
	public static Vector<SoapObject> getSoapObjectVectorByCallingWS(
			String nameSpace, String methodName, Map<String, Object> params,
			String wsdl) throws IOException, XmlPullParserException {
		return (Vector<SoapObject>) getObjectByCallingWS(nameSpace, methodName,
				params, wsdl);
	}

	public static SoapObject getSoapObjectByCallingWS(String nameSpace,
			String methodName, Map<String, Object> params, String wsdl)
			throws IOException, XmlPullParserException {
		return (SoapObject) getObjectByCallingWS(nameSpace, methodName, params,
				wsdl);
	}

	public static SoapPrimitive getSoapPrimitiveByCallingWS(String nameSpace,
			String methodName, Map<String, Object> params, String wsdl)
			throws IOException, XmlPullParserException {
		return (SoapPrimitive) getObjectByCallingWS(nameSpace, methodName,
				params, wsdl);
	}

	public static Object getObjectByCallingWS(String nameSpace,
			String methodName, Map<String, Object> params, String wsdl)
			throws IOException, XmlPullParserException {

		final String SOAP_ACTION = nameSpace + methodName;
		Object soapPrimitiveResult = null;

		SoapSerializationEnvelope envelope = constructRequestObject2(nameSpace,
				methodName, params);
		soapPrimitiveResult = callWebservice(SOAP_ACTION, wsdl, envelope);

		return soapPrimitiveResult;
	}

	private static SoapSerializationEnvelope constructRequestObject2(
			String nameSpace, String methodName, Map<String, Object> params) {
		<span style="color:#ff0000;">SoapObject request = new SoapObject(nameSpace, methodName);// 第一步,实例化SoapObject对象,并指定命名空间和方法名
</span>		if (params != null && !params.isEmpty()) {
			for (Iterator<Map.Entry<String, Object>> it = params.entrySet()
					.iterator(); it.hasNext();) {
				Map.Entry<String, Object> e = it.next();
				if (e.getValue() instanceof byte[]) {
					byte[] d = (byte[]) e.getValue();
					String data = new String(Base64.encode(d));
					// request.addProperty(e.getKey(), new
					// SoapPrimitive(SoapEnvelope.ENC, "base64Binary", data));
					<span style="color:#ff0000;">request.addProperty(e.getKey(), data);// 第二步,设置调用参数方法,包括参数名称和参数值
</span>				} else {
					request.addProperty(e.getKey().toString(), e.getValue());
				}
			}
		}
		<span style="color:#ff0000;">// 第三步,设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用到的WEBSERVICE中的版本号一致)
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER10);
		envelope.setOutputSoapObject(request);

</span>		// envelope.bodyOut = request;
		envelope.dotNet = true;
		envelope.encodingStyle = SoapSerializationEnvelope.ENC;
		return envelope;
	}

	public static SoapPrimitive getSoapPrimitiveByCallingWSWithFile(
			String nameSpace, String methodName, Map<String, Object> params,
			String wsdl) throws IOException, XmlPullParserException {

		final String SOAP_ACTION = nameSpace + methodName;
		SoapPrimitive soapPrimitiveResult = null;

		SoapObject request = constructRequestObjectWithFile(nameSpace,
				methodName, params);
		SoapSerializationEnvelope envelope = getEncEnvelope(request);
		soapPrimitiveResult = (SoapPrimitive) callWebservice(SOAP_ACTION, wsdl,
				envelope);

		return soapPrimitiveResult;
	}

	public static Object callWebservice(String SOAP_ACTION, String wsdl,
			SoapSerializationEnvelope envelope) throws IOException,
			XmlPullParserException {

		// registerObjects(envelope);
		Object resultObject = null;
		<span style="color:#ff0000;">HttpTransportSE ht = new HttpTransportSE(wsdl); // 第四步,构建传输对象,并指明wsdl文档url
</span>		try {
			<span style="color:#ff0000;">ht.call(SOAP_ACTION, envelope);// 第五步,调用webservice(其中参数一SOAP_ACTION为命名空间+方法名,参数二为envelope)

</span>		} catch (IOException e) {
			Log.e("IOException:", e.getMessage());
			// androidHT.reset();
			throw e;
		} catch (XmlPullParserException e1) {
			Log.e("XmlPullParserException", e1.getMessage());
			throw e1;
		}
		try {
			<span style="color:#ff0000;">resultObject = envelope.getResponse();// 第6步:使用getResponse方法获得WebService方法的返回结果
</span>		} catch (SoapFault e) {
			Log.e("SoapFault", e.getMessage());
		}
		return resultObject;
	}

	public static SoapObject constructRequestObject(String nameSpace,
			String methodName, Map<String, Object> params) {

		SoapObject request = new SoapObject(nameSpace, methodName);

		if (params != null && !params.isEmpty()) {
			for (Iterator<Map.Entry<String, Object>> it = params.entrySet()
					.iterator(); it.hasNext();) {
				Map.Entry<String, Object> e = it.next();
				request.addProperty(e.getKey().toString(), e.getValue());
			}
		}
		return request;
	}

	public static SoapObject constructRequestObjectWithFile(String nameSpace,
			String methodName, Map<String, Object> params) {

		SoapObject request = new SoapObject(nameSpace, methodName);
		if (params != null && !params.isEmpty()) {
			for (Iterator<Map.Entry<String, Object>> it = params.entrySet()
					.iterator(); it.hasNext();) {
				Map.Entry<String, Object> e = it.next();
				if (e.getValue() instanceof byte[]) {
					byte[] d = (byte[]) e.getValue();
					String data = new String(Base64.encode(d));
					request.addProperty(e.getKey(), new SoapPrimitive(
							SoapEnvelope.ENC, "base64Binary", data));
				} else {
					request.addProperty(e.getKey().toString(), e.getValue());
				}
			}
		}
		return request;
	}

	public static SoapSerializationEnvelope getEncEnvelope(SoapObject request) {

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

		// envelope.bodyOut = request;
		envelope.dotNet = true;
		envelope.encodingStyle = SoapSerializationEnvelope.ENC;
		return envelope;
	}

	public static SoapSerializationEnvelope getEnvelope(SoapObject request) {

		// SoapSerializationEnvelope envelope=new
		// SoapSerializationEnvelope(SoapEnvelope.VER10);//SOAP 1.0
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER10);// SOAP 1.1
		// SoapSerializationEnvelope envelope=new
		// SoapSerializationEnvelope(SoapEnvelope.VER12);//SOAP 1.2

		envelope.dotNet = true;
		// envelope.bodyOut = request;
		envelope.setOutputSoapObject(request);

		return envelope;
	}

	public static Map<String, String> getDatabyWebservicesMap(
			Activity activity, HashMap<String, Object> params, String servies) {

		SoapObject queryResult = null;
		ArrayList<List<String>> rows = null;

		try {
			queryResult = WSUtil.getSoapObjectByCallingWS(
					WebServiceConfig.NAMESPACE, servies, params,
					WebServiceConfig.wsdl);
		} catch (Exception e) {
			/*
			 * new
			 * AlertDialog.Builder(activity.getApplicationContext()).setTitle
			 * (R.string.message_title) .setMessage(R.string.connection_error)
			 * .setPositiveButton(R.string.OK_text, null).show();
			 * activity.finish();
			 */
			// return;
		}

		return WSUtil.handleResultMap(queryResult);
	}

	public static Map<String, String> handleResultMap(SoapObject queryResult) {
		WSObjectUtil wsObjectUtil = new WSObjectUtil();
		SoapObject dataset = WSUtil.getDataRow(queryResult, 0);

		if (dataset == null) {
			// noResult();
			return null;
		}
		return (Map<String, String>) WSUtil.getPropertiesMap(dataset);
	}

	public static SoapObject getDataRow(SoapObject o, Integer index) {
		SoapObject row = null;

		try {
			SoapObject diffgram = (SoapObject) o.getProperty(1);
			SoapObject rows = (SoapObject) diffgram.getProperty(0);
			row = (SoapObject) rows.getProperty(index);
		} catch (Exception e) {
			Log.e("Exception", e.getMessage());
		}
		return row;
	}

	public static Map<String, String> getPropertiesMap(SoapObject o) {
		Map<String, String> propertiesMap = new HashMap<String, String>();

		for (int i = 0; i < o.getPropertyCount(); i++) {
			PropertyInfo propertyInfo = new PropertyInfo();
			o.getPropertyInfo(i, propertyInfo);
			String propertyName = propertyInfo.getName();
			propertiesMap.put(propertyName, o.getProperty(i).toString());
		}

		return propertiesMap;
	}

	public static ArrayList<List<String>> handleResult(SoapObject queryResult) {
		WSObjectUtil wsObjectUtil = new WSObjectUtil();
		SoapObject dataset = wsObjectUtil.getDataTableObject(queryResult);

		if (dataset == null) {
			// noResult();
			return null;
		}
		ArrayList<List<String>> rowparameter = new ArrayList<List<String>>();
		rowparameter = (ArrayList<List<String>>) WSUtil
				.getPropertiesTableList(dataset);
		return rowparameter;
	}

	public static List<List<String>> getPropertiesTableList(SoapObject o) {
		List<List<String>> propertiesTableList = new ArrayList<List<String>>();

		try {
			for (int i = 0; i < o.getPropertyCount(); i++) {
				propertiesTableList.add(getPropertiesList((SoapObject) o
						.getProperty(i)));
			}
		} catch (Exception e) {
			Log.e("Exception", e.getMessage());
		}

		return propertiesTableList;
	}

	public static List<String> getPropertiesList(SoapObject o) {
		List<String> propertiesList = new ArrayList<String>();

		try {
			for (int i = 0; i < o.getPropertyCount(); i++) {
				propertiesList.add(o.getProperty(i).toString());
			}
		} catch (Exception e) {
			Log.e("Exception", e.getMessage());
		}

		return propertiesList;
	}
}


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

得到第六步返回的结果。

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



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

    [WebMethod(Description = "Android 接口: 登陆 userName 用户名 userPwd 用户密码")]  
            public DataSet login(string userName, string userPwd)  
            {  
                DataSet ds = null;  
      
                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);  
                try  
                {  
                    RetStrSql(strSql);  
                    ds = RetDataSet();  
                    return ds;  
                }  
                catch (Exception ex)  
                {  
                    //throw new Exception(ex.Message);  
                    return null;  
      
                }  
            }  


本文转自:http://blog.csdn.net/jindegegesun/article/details/7267813

分享到:
评论

相关推荐

    android 调用 Webservice源码

    在Android开发中,有时我们需要与服务器进行数据交互,这时候Webservice接口就显得尤为重要。本教程主要涉及如何在Android端调用Webservice服务,通过提供的源码实现基础的数学运算,如加、减、乘、除,并对相关技术...

    Android调用webservice进行实体对象的传递Json

    本文将探讨如何在Android中调用WebService并使用JSON来安全地传输实体对象。首先,我们依赖于两个类库:ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar用于Android端,而Newtonsoft.Json.dll则用于服务端...

    android 访问webService Demo

    在这个“android 访问webService Demo”中,我们将探讨如何在Android应用中集成和使用Web Service,尤其适合初学者快速上手。 一、理解Web Service Web Service是一种跨平台的通信机制,它允许不同的应用程序通过...

    android webService

    在Android开发中,Web服务(通常指WebService)是一种允许应用程序之间进行交互的技术,它使得移动应用,如Android应用,能够与远程服务器进行数据交换。在本案例中,开发者遇到了一个常见的问题:`java.lang....

    Android配合WebService(包含包)

    标题提到的“Android配合WebService例子”意味着我们将探讨如何在Android应用中集成并使用Web Service。 首先,我们要了解什么是Web Service。Web Service是一种基于网络的、可互操作的软件接口,它允许不同系统...

    Android调用Webservice使用的ksoap2包

    总结,Ksoap2为Android开发者提供了一种简单的方式来调用.NET WebService,通过构建SOAP请求和解析响应,使得跨平台通信变得容易。然而,随着技术的发展,越来越多的Android应用倾向于使用基于JSON的RESTful API,...

    android平台调用webservice

    本主题将深入探讨如何在Android应用中调用Web服务,特别是基于SOAP协议的Web服务,即“Android与服务器端数据交互(基于SOAP协议整合android+webservice)”。 SOAP(Simple Object Access Protocol)是一种轻量级...

    android调用webservice 的对象序列化代码

    在Android开发中,调用Web服务是常见的任务之一,尤其是使用WebService进行数据交换。Web服务通常采用SOAP(Simple Object Access Protocol)或RESTful API的形式,其中SOAP常常涉及到对象的序列化和反序列化。对象...

    webservice 和android 调用客户端

    以上就是关于"webservice和android调用客户端"的相关知识点,涵盖了WebService的基本原理、Android客户端调用WebService的流程、以及可能涉及的安全和优化措施。理解并掌握这些内容对于开发Android应用与服务器的...

    Android访问webservice

    在Android开发中,访问Web Service是一项常见的任务,主要用于实现客户端与服务器端的数据交互。Web Service是一种基于网络的、独立于平台的应用程序接口,它能够通过HTTP协议进行通信,允许不同系统间的互操作性。...

    Android 通过WebService进行网络编程的总结

    - 创建HttpTransportSE对象,调用其`call()`方法发送请求。 - 解析响应,获取数据。 2. **RESTful API**:REST(Representational State Transfer)是一种轻量级的架构风格,它基于HTTP协议,使用JSON或XML作为...

    Android访问webService框架

    androidHttpTransport.call("", envelope); return (SoapPrimitive) envelope.getResponse(); } } ``` 在这个示例中,`makeRequest`方法创建了一个SoapObject,而`callWebService`方法则负责发送请求并获取响应...

    Android客户端调用webService上传图片到服务器

    在Android客户端调用Web Service上传图片到服务器的过程中,主要涉及以下几个关键知识点: 1. **文件I/O操作**:客户端首先需要从SD卡或其他存储位置读取图片文件。这里使用`FileInputStream`读取图片文件,然后...

    android 调用.net webservice

    ### Android调用.NET WebService详解 #### 一、概述 在Android开发中,与服务器进行交互是必不可少的一个环节。常见的交互方式包括HTTP请求、RESTful API等,而WebService作为一种传统但依然广泛使用的通信协议,...

    android-webservice参考代码

    在Android开发中,Web服务(Web Service)是应用程序与服务器端数据交互的一种重要方式,它允许客户端(如Android应用)通过网络发送请求并接收响应数据。本参考代码着重讲解如何在Android平台上集成和使用Web服务,...

    Android调用WebService

    本文将深入探讨如何使用kSOAP库在Android应用中调用WebService,同时也会涉及利用Axis插件创建服务端的过程。 首先,让我们了解什么是kSOAP。kSOAP是一个轻量级的库,专为Android设计,用于处理SOAP(Simple Object...

    Android连接webservice测试代码

    根据提供的文件信息,我们可以归纳出以下关键知识点,这些知识点主要围绕Android应用如何通过Webservice进行数据交换。 ### 1. Webservice概念与作用 - **Webservice定义**:Webservice是一种跨编程语言和操作系统...

    android与C# WebService基于ksoap通信

    总结,Android与C# WebService基于kSOAP通信的核心在于正确构造SOAP请求,设置HTTP头信息,调用Web Service方法,发送请求并处理响应。这个过程中需要注意兼容性问题,特别是当Android客户端与.NET Web Service交互...

    android调用webservice获取手机归属地

    本教程将详细介绍如何在Android应用中调用WebService来获取手机归属地。 1. **理解WebService** WebService是一种基于互联网的、平台无关的服务,它允许不同系统间的应用程序之间进行通信。常见的WebService技术有...

Global site tag (gtag.js) - Google Analytics