尽量写的简单些,希望对大家有所帮助。
一、下载 KSOAP2 包地址: http://code.google.com/p/ksoap2-android/source/browse/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/2.5.4/ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar ,点击右下角的 View raw file 链接下载。
二、将 KSOAP2 包添加到 Eclipse 中,右键单击我们需要添加 KSOAP2 包的工程——>单击 "Build Path" ——>单击 "Configure Build Path..." 。添加成功如图所示:
三、怎样去调用 WebService 中的方法,代码实现如下:
package com.treasure.train.transport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import com.treasure.train.meta.Constant;
public class WebServiceHelper {
/**
* 获得所有始发站的城市名称
* @return
*/
public static List<String> getAllStartStationCityNames()
{
List<String> cityNames = new ArrayList<String>();
SoapObject soapObject = new SoapObject(Constant.URL, Constant.getStationName);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = soapObject;
envelope.dotNet = true;
envelope.setOutputSoapObject(soapObject);
HttpTransportSE httpTranstation = new HttpTransportSE(Constant.URL);
httpTranstation.debug = true;
try {
httpTranstation.call(Constant.SOAP_ACTION, envelope);
SoapObject result = (SoapObject)envelope.getResponse();
// 下面对结果进行解析。
int count = result.getPropertyCount();
for (int index = 0; index < count; index++)
{
cityNames.add(result.getProperty(index).toString());
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return cityNames;
}
}
Constant.java, 代码如下:
package com.treasure.train.meta;
public class Constant {
// 命名空间
public static final String NAMESPACE = "http://WebXml.com.cn/";
// 获得本火车时刻表Web Service 的全部始发站名称
public static final String getStationName = "getStationName";
// 请求URL
public static final String URL = "http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx";
// 用于调用WebService,形式是:命名空间+方法名称(参数1)
public static final String SOAP_ACTION = "http://WebXml.com.cn/getStationName";
}
四、最后在 AndroidManifest.xml 加入访问 Internet 权限。代码如下:
<uses-permission android:name="android.permission.INTERNET"/>