android 调用webService Demo

来源:互联网 发布:年底做网络推广的好处 编辑:程序博客网 时间:2024/05/16 06:52

1、添加网络访问权限在AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

2、加入soap的jia包ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar

下载地址http://download.csdn.net/detail/yusewuhen/8423905

3、 创建字段

// 名空间private static final String NAMESPACE   = "http://WebXml.com.cn/";// 网址private static String  URL      = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";// 方法名private static final String METHOD_NAME = "getWeather";// SOAPACTIONprivate static String  SOAP_ACTION = "http://WebXml.com.cn/getWeather";

4、       获取Soap对象并设置传送参数值

SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);rpc.addProperty("theCityCode", cityName);

5、    创建SoapSerializationEnvelope对象

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);envelope.bodyOut = rpc;envelope.dotNet = true;envelope.setOutputSoapObject(rpc);//其中SoapEnvelope.VER11是指SOAP 1.1,

6、创建HttpTransportsSE对象

HttpTransportSE ht = new HttpTransportSE(URL);ht.debug = true;//对于部分不规范的webService需要使用ht.call(null, envelope); ht.call(SOAP_ACTION, envelope);

7、获得WebService方法的返回结果

方法一:

detail =(SoapObject) envelope.getResponse();

方法二:

SoapObject result = (SoapObject)envelope.bodyIn;

detail = (SoapObject) result.getProperty("getWeatherbyCityNameResult");

 8、解析SoapObject对象

if(envelope.getResponse()!=null){
SoapObject  detail =(SoapObject) envelope.bodyIn;

for (int i = 0; i < detail.getPropertyCount(); i++) {

     System.out.println("detail.getProperty(" + i + ")" + detail.getProperty(i));

}}

可测试的webservice服务

http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx

页面中有以下信息:

getWeather

获得天气预报数据

输入参数:城市/地区ID或名称,返回数据:一维字符串数组

点击getWeather

http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx?op=getWeather

从上述页面可以获取以下信息:

SOAPAction: "http://WebXml.com.cn/getWeather"<getWeather xmlns="http://WebXml.com.cn/">其中xmlns就是NAMESPACE值以及传送参数名theCityCode




0 0
原创粉丝点击