Android 连接.net WebService 工具类代码

安卓代码:

import android.os.Handler;
import android.os.Message;


import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

public class WebServiceUtils {
public interface CallBack {
void result(String result);
}
//参数说明,serviceUrl是.net的webservice地址,一般取得是http://IP地址:端口号/XXX.asmx
// methodName 是WebService上的接口名
// okparams 是 传递的参数以String的形式传递,传递Json可以先转为字符串,服务端再解析出来
//CallBack回调,获取返回的值
    public static void getResult(final String serviceUrl,final String methodName,final String okparams, final CallBack callBack) {
// 用于子线程与主线程通信的Handler
final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 将返回值回调到callBack的参数中
callBack.result((String) msg.obj);
}
};
new Thread(new Runnable() {
@Override
public void run() {

try{
//.net上的命名空间+webwervice上的方法名
String soapAction = "http://tempuri.org/" + methodName;
//参数,命名空间,方法名
SoapObject request = new SoapObject("http://tempuri.org/", methodName);
//传递的参数,注意key要与.net方法的参数名一致
request.addProperty("okparams",okparams );
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = request;
HttpTransportSE ht = new HttpTransportSE(serviceUrl);
ht.call(soapAction, envelope);
Object object;
if (envelope.getResponse() != null){
object = (Object)envelope.getResponse();
// SoapObject soapObject = (SoapObject) envelope.getResponse();
// 将结果利用Handler发送到主线程
mHandler.sendMessage(mHandler.obtainMessage(1, object.toString()));

}
if (envelope.bodyIn instanceof SoapFault) {
SoapFault error = (SoapFault) envelope.bodyIn;
// 将异常的消息利用Handler发送到主线程
mHandler.sendMessage(mHandler.obtainMessage(0, error.toString()));
}

}catch (Exception ex)
{
mHandler.sendMessage(mHandler.obtainMessage(-1, ex.getMessage()));
}

}
}).start();
}
}



//使用实例

WebServiceUtils.getResult(serviceUrl, methodName, 传递的参数, new WebServiceUtils.CallBack() {
@Override
public void result(String result) {
//返回值
String res = result;

}
});


//.Net部分代码

///


/// test 的摘要说明
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class test : System.Web.Services.WebService
{

     [WebMethod]

    public string HelloWorld(string okparams)
   {

        return "Hello World";
  }

  

 

}







你可能感兴趣的:(Android 连接.net WebService 工具类代码)