本文轉自:http://danielzzu.blog.163.com/blog/static/118515304201011103562841/
在企業應用中,手機與企業數據的交互必不可少,在這里我們通過實例來描述android怎樣調用.net webservice
第一步:vs2008建webservice ,貼出代碼:
clsoptuser.cs
public
class
clsoptuser
{
{
//驗證方法
public bool Validate( string u, string p)
{
bool k = false ;
SqlConnection userConn = new SqlConnection( " 連接字符 " );
userConn.Open();
SqlCommand userComm = new SqlCommand( " select *from user " , userConn);
SqlDataReader userDr = userComm.ExecuteReader();
string tmpuser, tmppass;
while (userDr.Read())
{
int userindex = userDr.GetOrdinal( " user " );
int passindex = userDr.GetOrdinal( " password " );
tmpuser = userDr.GetString(userindex);
tmppass = userDr.GetString(passindex);
public bool Validate( string u, string p)
{
bool k = false ;
SqlConnection userConn = new SqlConnection( " 連接字符 " );
userConn.Open();
SqlCommand userComm = new SqlCommand( " select *from user " , userConn);
SqlDataReader userDr = userComm.ExecuteReader();
string tmpuser, tmppass;
while (userDr.Read())
{
int userindex = userDr.GetOrdinal( " user " );
int passindex = userDr.GetOrdinal( " password " );
tmpuser = userDr.GetString(userindex);
tmppass = userDr.GetString(passindex);
//用戶名和口令正確返回true
if ((tmpuser == u) && (tmppass == p))
{
k = true ;
break ;
}
}
return k;
}
}
if ((tmpuser == u) && (tmppass == p))
{
k = true ;
break ;
}
}
return k;
}
}

[WebMethod]
public bool ValidateUsername( string username, string pass, string validate)
{
if (validate == " webservice驗證碼 " )
{
clsoptuser objoptuser = new clsoptuser();
return objoptuser.Validate(username, pass);
}
else
{
return false ;
}
}
public bool ValidateUsername( string username, string pass, string validate)
{
if (validate == " webservice驗證碼 " )
{
clsoptuser objoptuser = new clsoptuser();
return objoptuser.Validate(username, pass);
}
else
{
return false ;
}
}
以上是服務器端的代碼,把上面程序布署到IIS,布署以后可以用IE測試,具體布署我就不說了,網上到處有!
第二步:android客戶端
android調用webservice 要用到ksoap2-android-assembly-2.4-jar-with-dependencies.jar一個包,到網上可下載,然后在Eclipce項目中添加處部jar
1、布局文件
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 "
< LinearLayout xmlns:android = " http://schemas.android.com/apk/res/android "
android:orientation = " vertical "
android:layout_width = " fill_parent "
android:layout_height = " fill_parent "
android:background
=
"
@drawable/login2
"
android:gravity
=
"
bottom
"
>
< LinearLayout android:id = " @+id/LinearLayout02 "
android:layout_height = " wrap_content "
android:layout_width = " fill_parent " >
< TextView android:layout_width = " wrap_content "
android:layout_height = " wrap_content "
android:id = " @+id/labeluser "
android:text = " @string/labelname "
android:textStyle = " bold "
android:textSize = " 20sp " >
</ TextView >
< EditText android:layout_height = " wrap_content "
android:id = " @+id/EditTextUser "
android:width = " 150px "
android:layout_width = " fill_parent " >
</ EditText >
</ LinearLayout >
< LinearLayout android:id = " @+id/LinearLayout03 "
android:layout_height = " wrap_content "
android:layout_width = " fill_parent " >
< TextView android:layout_width = " wrap_content "
android:layout_height = " wrap_content "
android:id = " @+id/labelpass "
android:text = " 登錄密碼: "
android:textStyle = " bold "
android:textSize = " 20sp " >
</ TextView >
< EditText android:layout_height = " wrap_content "
android:id = " @+id/EditTextPassWord "
android:password = " true "
android:layout_width = " fill_parent " >
</ EditText >
</ LinearLayout >
< LinearLayout android:id = " @+id/LinearLayout04 "
< LinearLayout android:id = " @+id/LinearLayout02 "
android:layout_height = " wrap_content "
android:layout_width = " fill_parent " >
< TextView android:layout_width = " wrap_content "
android:layout_height = " wrap_content "
android:id = " @+id/labeluser "
android:text = " @string/labelname "
android:textStyle = " bold "
android:textSize = " 20sp " >
</ TextView >
< EditText android:layout_height = " wrap_content "
android:id = " @+id/EditTextUser "
android:width = " 150px "
android:layout_width = " fill_parent " >
</ EditText >
</ LinearLayout >
< LinearLayout android:id = " @+id/LinearLayout03 "
android:layout_height = " wrap_content "
android:layout_width = " fill_parent " >
< TextView android:layout_width = " wrap_content "
android:layout_height = " wrap_content "
android:id = " @+id/labelpass "
android:text = " 登錄密碼: "
android:textStyle = " bold "
android:textSize = " 20sp " >
</ TextView >
< EditText android:layout_height = " wrap_content "
android:id = " @+id/EditTextPassWord "
android:password = " true "
android:layout_width = " fill_parent " >
</ EditText >
</ LinearLayout >
< LinearLayout android:id = " @+id/LinearLayout04 "
android:layout_height
=
"
wrap_content
"
android:layout_width
=
"
fill_parent
"
android:gravity
=
"
center
"
>
<
CheckBox android:id
=
"
@+id/CheckBox01
"
android:layout_width
=
"
wrap_content
"
android:layout_height
=
"
wrap_content
"
android:text
=
"
記住用戶名和密碼
"
android:
checked
=
"
true
"
>
</
CheckBox
>
</ LinearLayout >
< LinearLayout android:id = " @+id/LinearLayout01 "
</ LinearLayout >
< LinearLayout android:id = " @+id/LinearLayout01 "
android:layout_height
=
"
wrap_content
"
android:layout_width
=
"
fill_parent
"
android:layout_gravity
=
"
bottom
"
android:gravity
=
"
center
"
>
<
Button android:id
=
"
@+id/BtnLogin
"
android:text
=
"
登 錄
"
android:layout_height
=
"
wrap_content
"
android:layout_width
=
"
wrap_content
"
android:layout_weight
=
"
1
"
>
</
Button
>
<
Button android:layout_width
=
"
wrap_content
"
android:layout_height
=
"
wrap_content
"
android:id
=
"
@+id/BtnExit
"
android:text
=
"
退 出
"
android:layout_weight
=
"
1
"
>
</
Button
>
</ LinearLayout >
</ LinearLayout >
</ LinearLayout >
</ LinearLayout >
想到每次進系統都要輸入用戶名和密碼都恐怖(android的虛擬鍵盤確實不怎的),所以上面加了個"記住用戶名和密碼",方便下次不用輸用戶名和密碼.
2、login.java

package
com.liwei.login;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import com.liwei.prohotel.clswdy.HttpThread;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class login extends Activity {
Button btnlogin,btnexit; //登錄和退出按鈕對像
EditText edituser,editpass; //用戶名和密碼輸入框對象
boolean data = false ; //調用webservice 近回的數據,驗證成功true,失敗false
HttpThread thread = null ; //線程對像
String name = "" ; //用戶名
String pass = "" ; //口令
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.main);
btnlogin = (Button)findViewById(R.id.BtnLogin); //獲得用戶名和密碼按鈕實例
btnexit = (Button)findViewById(R.id.BtnExit);
edituser = (EditText)findViewById(R.id.EditTextUser); //獲得用戶名和密碼Edittext
editpass = (EditText)findViewById(R.id.EditTextPassWord);
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import com.liwei.prohotel.clswdy.HttpThread;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class login extends Activity {
Button btnlogin,btnexit; //登錄和退出按鈕對像
EditText edituser,editpass; //用戶名和密碼輸入框對象
boolean data = false ; //調用webservice 近回的數據,驗證成功true,失敗false
HttpThread thread = null ; //線程對像
String name = "" ; //用戶名
String pass = "" ; //口令
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.main);
btnlogin = (Button)findViewById(R.id.BtnLogin); //獲得用戶名和密碼按鈕實例
btnexit = (Button)findViewById(R.id.BtnExit);
edituser = (EditText)findViewById(R.id.EditTextUser); //獲得用戶名和密碼Edittext
editpass = (EditText)findViewById(R.id.EditTextPassWord);
//獲取上次保存的用戶名和密碼
SharedPreferences sp = getSharedPreferences( " login " ,Context.MODE_PRIVATE);
String tempstr = sp.getString( " username " , "" );
edituser.setText(tempstr);
editpass.setText(sp.getString( " pass " , "" ));
SharedPreferences sp = getSharedPreferences( " login " ,Context.MODE_PRIVATE);
String tempstr = sp.getString( " username " , "" );
edituser.setText(tempstr);
editpass.setText(sp.getString( " pass " , "" ));
//退出按鈕點擊事件
btnexit.setOnClickListener( new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
//登錄按鈕點擊事件
btnlogin.setOnClickListener( new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
name = edituser.getText().toString();
pass = editpass.getText().toString();
ResponseOnClickLogin(name, pass);
}
});
}
btnexit.setOnClickListener( new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
//登錄按鈕點擊事件
btnlogin.setOnClickListener( new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
name = edituser.getText().toString();
pass = editpass.getText().toString();
ResponseOnClickLogin(name, pass);
}
});
}
public void ResponseOnClickLogin(String username,String password){
thread = new HttpThread(handlerwdy); //建立線程實例
HashMap < String ,Object > params = new HashMap < String ,Object > ();
try{
String strvalidate
=
"
galyglxxxt
"
;
strvalidate = new String(strvalidate.toString().getBytes(), " UTF-8 " );
params.put( " username " , username); // 加入參數
params.put( " pass " , password);
params.put( " validate " , strvalidate);
} catch (Exception ex){
ex.printStackTrace();
}
String url = " 192.168.3.2:8080/loginweb/service.asmx " ;//webserivce地址
String nameSpace = " http://tempuri.org/ " ; //空間名,可修改
String methodName = " ValidateUsername " ; //需調用webservice名稱
thread.doStart(url, nameSpace, methodName, params); //啟動線程
}
strvalidate = new String(strvalidate.toString().getBytes(), " UTF-8 " );
params.put( " username " , username); // 加入參數
params.put( " pass " , password);
params.put( " validate " , strvalidate);
} catch (Exception ex){
ex.printStackTrace();
}
String url = " 192.168.3.2:8080/loginweb/service.asmx " ;//webserivce地址
String nameSpace = " http://tempuri.org/ " ; //空間名,可修改
String methodName = " ValidateUsername " ; //需調用webservice名稱
thread.doStart(url, nameSpace, methodName, params); //啟動線程
}
//生成消息對象
Handler handlerwdy = new Handler(){
public void handleMessage(Message m){
switch (m.what){
case 1 :
data = m.getData().getBoolean( " data " ); //從消息在拿出數據
if (data){
CheckBox cb = (CheckBox)findViewById(R.id.CheckBox01); //如果要保存用戶名和密碼
if (cb.isChecked())
{
SharedPreferences sp = getSharedPreferences( " login " ,Context.MODE_PRIVATE);
Editor editor = sp.edit();
String tempname = name;
editor.putString( " username " , name);
editor.putString( " pass " , pass);
editor.commit();
}
else
{
SharedPreferences sp = getSharedPreferences( " login " ,Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString( " username " , "" );
editor.putString( " pass " , "" );
editor.commit();
}
Handler handlerwdy = new Handler(){
public void handleMessage(Message m){
switch (m.what){
case 1 :
data = m.getData().getBoolean( " data " ); //從消息在拿出數據
if (data){
CheckBox cb = (CheckBox)findViewById(R.id.CheckBox01); //如果要保存用戶名和密碼
if (cb.isChecked())
{
SharedPreferences sp = getSharedPreferences( " login " ,Context.MODE_PRIVATE);
Editor editor = sp.edit();
String tempname = name;
editor.putString( " username " , name);
editor.putString( " pass " , pass);
editor.commit();
}
else
{
SharedPreferences sp = getSharedPreferences( " login " ,Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString( " username " , "" );
editor.putString( " pass " , "" );
editor.commit();
}
//登錄成功后的提示
Toast.makeText(prohotel. this , getString(R.string.login_message), Toast.LENGTH_SHORT)
.show();
Toast.makeText(prohotel. this , getString(R.string.login_message), Toast.LENGTH_SHORT)
.show();
//成功后界面要交給項目的主界面了
Intent in = new Intent(prohotel. this ,promain. class );
//把用戶名傳給下一個activity
Bundle bundle = new Bundle();
bundle.putString( " KEY_USERNAME " ,name);
in.putExtras(bundle);
login. this .startActivity(in);
}
else
{
Intent in = new Intent(prohotel. this ,promain. class );
//把用戶名傳給下一個activity
Bundle bundle = new Bundle();
bundle.putString( " KEY_USERNAME " ,name);
in.putExtras(bundle);
login. this .startActivity(in);
}
else
{
//驗證不通過,給出個提示
SharedPreferences sp = getSharedPreferences( " login " ,Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString( " username " , "" );
editor.putString( " pass " , "" );
editor.commit();
new AlertDialog.Builder(prohotel. this )
.setTitle(getString(R.string.login_message_title))
.setMessage(getString(R.string.login_message_title))
.setIcon(R.drawable.cancel)
.setNeutralButton(getString(R.string.login_button_text), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
// do nothing ?C it will close on its own
}
})
.show();
}
break ;
case 2 :
SharedPreferences sp = getSharedPreferences( " login " ,Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString( " username " , "" );
editor.putString( " pass " , "" );
editor.commit();
new AlertDialog.Builder(prohotel. this )
.setTitle(getString(R.string.login_message_title))
.setMessage(getString(R.string.login_message_title))
.setIcon(R.drawable.cancel)
.setNeutralButton(getString(R.string.login_button_text), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
// do nothing ?C it will close on its own
}
})
.show();
}
break ;
case 2 :
//收到了調用出錯的消息
new AlertDialog.Builder(prohotel. this )
.setTitle( " 出錯: " )
.setMessage(m.getData().getString( " error " ))
.setNeutralButton( " Close " , new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
// do nothing ?C it will close on its own
}
})
.show();
break ;
}
}
};
new AlertDialog.Builder(prohotel. this )
.setTitle( " 出錯: " )
.setMessage(m.getData().getString( " error " ))
.setNeutralButton( " Close " , new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
// do nothing ?C it will close on its own
}
})
.show();
break ;
}
}
};
//線程類
public class HttpThread extends Thread{
private Handler handle = null ;
String url = null ;
String nameSpace = null ;
String methodName = null ;
HashMap < String ,Object > params = null ;
ProgressDialog progressDialog = null ;
public HttpThread(Handler hander){
handle = hander;
}
//線程開始
public void doStart(String url, String nameSpace, String methodName,
HashMap < String, Object > params) {
// 把參數傳進來
this .url = url;
this .nameSpace = nameSpace;
this .methodName = methodName;
this .params = params;
//告訴使用者,請求開始了
progressDialog = new ProgressDialog(prohotel. this );
progressDialog.setTitle( " 網絡連接 " );
progressDialog.setMessage( " 正在請求,請稍等...... " );
progressDialog.setIndeterminate( true );
// progressDialog=ProgressDialog.show(clswdy.this, "網絡連接","正在驗證,請稍等......",true,true);
progressDialog.setButton( " 取消 " , new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
progressDialog.cancel();
}
});
progressDialog.setOnCancelListener( new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
}
});
progressDialog.show();
this .start(); //線程開始了
}
/**
*/
@Override
public void run() {
// TODO Auto-generated method stub
super .run();
try {
// web service請求,result為返回結果
boolean result = CallWebService();
if (result){
// 取消進度對話框
progressDialog.dismiss();
// clswdy.this.setProgressBarIndeterminateVisibility(false);
// 構造消息,驗證通過了
Message message = handle.obtainMessage();
Bundle b = new Bundle();
message.what = 1 ; //這里是消息的類型
b.putBoolean( " data " , true ); //這里是消息傳送的數據
message.setData(b);
handle.sendMessage(message);
}
else
{
progressDialog.dismiss();
Message message = handle.obtainMessage();
Bundle b = new Bundle();
message.what = 1 ;
b.putBoolean( " data " , false );
message.setData(b);
handle.sendMessage(message);
}
} catch (Exception ex){
progressDialog.dismiss();
// 構造消息,程序出錯了
Message message = handle.obtainMessage();
Bundle b = new Bundle();
message.what = 2 ;
b.putString( " error " , ex.getMessage());
message.setData(b);
handle.sendMessage(message);
} finally {
}
}
/**
*
*/
protected boolean CallWebService() throws Exception{
String SOAP_ACTION = nameSpace + methodName;
boolean response = false ;
SoapObject request = new SoapObject(nameSpace,methodName);
// boolean request=false;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true ; //.net 支持
// 參數
if (params != null && ! params.isEmpty() ){
for (Iterator it = params.entrySet().iterator();it.hasNext();){
Map.Entry e = (Entry) it.next();
request.addProperty(e.getKey().toString(),e.getValue());
}
}
envelope.bodyOut = request;
//
AndroidHttpTransport androidHttpTrandsport = new AndroidHttpTransport(url);
// HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
SoapObject result = null ;
try {
// web service請求
androidHttpTrandsport.call(SOAP_ACTION, envelope);
// 得到返回結果
Object temp = envelope.getResult();
response = Boolean.parseBoolean(temp.toString());
} catch (Exception ex){
throw ex;
}
return response;
}
}
}
public class HttpThread extends Thread{
private Handler handle = null ;
String url = null ;
String nameSpace = null ;
String methodName = null ;
HashMap < String ,Object > params = null ;
ProgressDialog progressDialog = null ;
public HttpThread(Handler hander){
handle = hander;
}
//線程開始
public void doStart(String url, String nameSpace, String methodName,
HashMap < String, Object > params) {
// 把參數傳進來
this .url = url;
this .nameSpace = nameSpace;
this .methodName = methodName;
this .params = params;
//告訴使用者,請求開始了
progressDialog = new ProgressDialog(prohotel. this );
progressDialog.setTitle( " 網絡連接 " );
progressDialog.setMessage( " 正在請求,請稍等...... " );
progressDialog.setIndeterminate( true );
// progressDialog=ProgressDialog.show(clswdy.this, "網絡連接","正在驗證,請稍等......",true,true);
progressDialog.setButton( " 取消 " , new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
progressDialog.cancel();
}
});
progressDialog.setOnCancelListener( new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
}
});
progressDialog.show();
this .start(); //線程開始了
}
/**
*/
@Override
public void run() {
// TODO Auto-generated method stub
super .run();
try {
// web service請求,result為返回結果
boolean result = CallWebService();
if (result){
// 取消進度對話框
progressDialog.dismiss();
// clswdy.this.setProgressBarIndeterminateVisibility(false);
// 構造消息,驗證通過了
Message message = handle.obtainMessage();
Bundle b = new Bundle();
message.what = 1 ; //這里是消息的類型
b.putBoolean( " data " , true ); //這里是消息傳送的數據
message.setData(b);
handle.sendMessage(message);
}
else
{
progressDialog.dismiss();
Message message = handle.obtainMessage();
Bundle b = new Bundle();
message.what = 1 ;
b.putBoolean( " data " , false );
message.setData(b);
handle.sendMessage(message);
}
} catch (Exception ex){
progressDialog.dismiss();
// 構造消息,程序出錯了
Message message = handle.obtainMessage();
Bundle b = new Bundle();
message.what = 2 ;
b.putString( " error " , ex.getMessage());
message.setData(b);
handle.sendMessage(message);
} finally {
}
}
/**
*
*/
protected boolean CallWebService() throws Exception{
String SOAP_ACTION = nameSpace + methodName;
boolean response = false ;
SoapObject request = new SoapObject(nameSpace,methodName);
// boolean request=false;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true ; //.net 支持
// 參數
if (params != null && ! params.isEmpty() ){
for (Iterator it = params.entrySet().iterator();it.hasNext();){
Map.Entry e = (Entry) it.next();
request.addProperty(e.getKey().toString(),e.getValue());
}
}
envelope.bodyOut = request;
//
AndroidHttpTransport androidHttpTrandsport = new AndroidHttpTransport(url);
// HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
SoapObject result = null ;
try {
// web service請求
androidHttpTrandsport.call(SOAP_ACTION, envelope);
// 得到返回結果
Object temp = envelope.getResult();
response = Boolean.parseBoolean(temp.toString());
} catch (Exception ex){
throw ex;
}
return response;
}
}
}
以上驗證程序需要訪問網絡,別忘了在AndroidManifest.xml加入 <uses-permission android:name="android.permission.INTERNET" />