android系统中使用ksoap2-android客户端库操作Asp.net WebService

在java中使用的PC版WebService客户端库非常丰富,例如,Axis2、CXF等,但这些开发包对于android来说过于庞大,也未必很容易移植到android上。适合手机的WebService客户端SDK也有一些。本例使用了比较常用的KSOAP2。读者可以从如下的地址下载Android版的KSOAP2。
http://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2
将下载下来的包引用到android项目后就可以使用了,在引用jar包后可能会抛出警告"warning: Ignoring InnerClasses attribute for an anonymous inner class that doesn't come with an associated EnclosingMethod attribute. (This class was probably produced by a broken compiler.)”,在网上搜索了一下,这可能是因为版本的问题,但是不影响使用。好了废话不多说,直接上代码。
服务器端的webservice文件Demo.asmx
<%@ WebService Language="C#" Class="Demo" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] //若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 // [System.Web.Script.Services.ScriptService] public class Demo : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public string Add(int x, int y) { int z = x + y; return z.ToString(); } }
下面就是我测试用的手机端的代码了,首先来看我们的xml布局文件 demo.xml

Demo.java,在下面的代码中,如果你的WebService方法没有参数,可以把step2省略掉。
package com.studio.basf.android; 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 Demo extends Activity { private String NameSpace = "http://tempuri.org/"; private String MethodName = "Add"; private String url = "http://192.168.1.93/services/Demo.asmx"; private String soapAction = NameSpace + MethodName; private TextView tv; @Override protected void _disibledevent=>
运行结果如下
android系统中使用ksoap2-android客户端库操作Asp.net WebService
Tags: 

延伸阅读

最新评论

发表评论