代码
package com.testWebService;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class TestWebService extends Activity {
private static String NameSpace="http://tempuri.org/";//这个不要改
private static String u="http://10.0.2.2:1471";//请更换成你要访问的服务器地址
private static String webService="/Service1.asmx";//webService目录
private static String MethodName="HelloWorld";//要调用的webService方法
private static String soapAction=NameSpace+MethodName;
private static String url=u+webService;//最终要访问的网址
private TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.tv);
tv.setText(ws());
}
//webService操作要访问网络,所以最好是使用线程来做,这里只是示例,所以就不考虑了
private String ws(){
String result="";
try{
SoapObject request=new SoapObject(NameSpace,MethodName);//NameSpace
//webService方法中的参数,这个根据你的webservice来,可以没有。
//请注意,参数名称和参数类型,客户端和服务端一定要一致,否则将可能获取不到你想要的值
//request.addProperty("x",5);
//request.addProperty("y", 6);
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet=true;//访问.NET的webservice
envelope.setOutputSoapObject(request);
HttpTransportSE ht=new HttpTransportSE(url);
ht.call(soapAction, envelope);//调用call方法,访问webservice
if(envelope.getResponse()!=null){
SoapPrimitive response=(SoapPrimitive)envelope.getResponse();
//如果要返回对象集合,在服务端可以将对象或集合序列化成json字符串返回,这边再反序列化成对象或集合
result=response.toString();//这里获得了webService的返回值
}
}catch(Exception e){
result=e.getMessage();
}
return result;
}
}
注意要添加第三方类库,ksoap2-android-assembly-2.4-jar-with-dependencies.jar