Google为Android平台开发Web Service客户端提供了ksoap2-android项目,在这个网址下载开发包http://code.google.com/p/ksoap2-android/source/browse/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/3.1.0/ksoap2-android-assembly-3.1.0-jar-with-dependencies.jar

demo 中 获取天气的webservice 可能不能用 请求的时候报HTTP503 可以把这段代码注释带 获取省份 城市的webservice是可用的 或者去换个webservice地址

      Android开发联盟③ 433233634

使用 kspoap2-android调用webserice操作的步骤如下:

1、创建HttpTransportSE传输对象 传入webservice服务器地址

final HttpTransportSE httpSE = new HttpTransportSE(SERVER_URL);

2、 创建SoapObject对象,创建该对象时需要传入所要调用Wb Service的命名空间、Web Service方法名;如果有参数要传给Web Service服务器,调用SoapObject对象的addProperty(String name,Object value)方法来设置参数,该方法的name参数指定参数名;value参数指定参数值

SoapObject soapObject = new SoapObject(PACE, M_NAME);
soapObject.addProperty("byProvinceName ", citys);

3、创建SoapSerializationEnelope对象,并传入SOAP协议的版本号;并设置对象的bodyOut属性

final SoapSerializationEnvelope soapserial = new SoapSerializationEnvelope(SoapEnvelope.VER11);soapserial.bodyOut = soapObject;// 设置与.NET提供的Web service保持有良好的兼容性soapserial.dotNet = true;

6、调用HttpTransportSE对象的call()方法,其中call的第一个参数soapAction,第二个为SoapSerializationEvelope对象 调用远程Web Service;

// 调用HttpTransportSE对象的call方法来调用 webserice   httpSE.call(PACE + M_NAME, soapserial);
7、获取返回的信息,并解析
// 获取服务器响应返回的SOAP消息SoapObject result = (SoapObject) soapserial.bodyIn;SoapObject detail = (SoapObject) result.getProperty("getSupportProvinceResult");//解析返回信息for (int i = 0; i < detail.getPropertyCount(); i++) {citys.add(detail.getProperty(i).toString());}


实例:通过天气预报 Web 服务 http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

MainActivity.java

package com.example.webserviceteset;import java.util.List;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.widget.AdapterView;import android.widget.ImageView;import android.widget.TextView;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.ArrayAdapter;import android.widget.Spinner;public class MainActivity extends Activity {private Spinner city, citys;private List<String> listcity, listcitys, weater;// 分别显示近三天的天气信息和城市介绍private TextView cityNames1, cityNames2, cityNames3, cityjie;private ImageView weateImage1, weateImage2, weateImage3;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);citys = (Spinner) findViewById(R.id.citys);city = (Spinner) findViewById(R.id.city);cityNames1 = (TextView) findViewById(R.id.cityNames1);cityNames2 = (TextView) findViewById(R.id.cityNames2);cityNames3 = (TextView) findViewById(R.id.cityNames3);cityjie = (TextView) findViewById(R.id.cityjie);weateImage1 = (ImageView) findViewById(R.id.weateImage1);weateImage2 = (ImageView) findViewById(R.id.weateImage2);weateImage3 = (ImageView) findViewById(R.id.weateImage3);// cityNames1=(TextView)findViewById(R.i)listcitys = WebServiceTest.getCitys();ArrayAdapter<String> citysAdater = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, listcitys);citys.setAdapter(citysAdater);listcity = WebServiceTest.getCity(citys.getSelectedItem().toString());ArrayAdapter<String> cityAdater = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, listcity);city.setAdapter(cityAdater);citys.setOnItemSelectedListener(new OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {listcity = WebServiceTest.getCity(citys.getSelectedItem().toString());ArrayAdapter<String> cityAdater1 = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_multiple_choice,listcity);city.setAdapter(cityAdater1);}@Overridepublic void onNothingSelected(AdapterView<?> arg0) {// TODO Auto-generated method stub}});city.setOnItemSelectedListener(new OnItemSelectedListener() {// 返回数据: 一个一维数组 String(22),共有23个元素。@Overridepublic void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {weater = WebServiceTest.getWeather(city.getSelectedItem().toString());for (int i = 0; i < weater.size(); i++) {System.out.println("i=" + i + ":" + weater.get(i));}cityNames1.setText(weater.get(6) + "\n" + weater.get(5) + "\n"+ weater.get(7));cityNames1.setBackgroundResource(ChangeImageView.imageId(weater.get(8)));weateImage1.setImageResource(ChangeImageView.imageId(weater.get(8)));cityNames2.setText(weater.get(13) + "\n" + weater.get(12) + "\n"+ weater.get(14));cityNames2.setBackgroundResource(ChangeImageView.imageId(weater.get(15)));weateImage2.setImageResource(ChangeImageView.imageId(weater.get(15)));cityNames3.setText(weater.get(18) + "\n" + weater.get(17) + "\n"+ weater.get(19));cityNames3.setBackgroundResource(ChangeImageView.imageId(weater.get(20)));weateImage3.setImageResource(ChangeImageView.imageId(weater.get(21)));cityjie.setText(weater.get(22));}@Overridepublic void onNothingSelected(AdapterView<?> arg0) {// TODO Auto-generated method stub}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);return true;}}

WebServiceTest.java

package com.example.webserviceteset;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;import org.ksoap2.SoapEnvelope;import org.ksoap2.serialization.SoapObject;import org.ksoap2.serialization.SoapSerializationEnvelope;import org.ksoap2.transport.HttpTransportSE;public class WebServiceTest {// Webservice服务器地址private static final String SERVER_URL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";// 调用的webservice命令空间private static final String PACE = "http://WebXml.com.cn/";// 获取所有省份的方法名private static final String M_NAME = "getSupportProvince";// 获取省份包含的城市的方法名private static final String MC_NAME = "getSupportCity";// 获取天气详情的方法名private static final String W_NAME = "getWeatherbyCityName";/** *  * @return 所有省份 */public static List<String> getCitys() {// 创建HttpTransportSE传说对象 传入webservice服务器地址final HttpTransportSE httpSE = new HttpTransportSE(SERVER_URL);httpSE.debug = true;// 创建soapObject对象并传入命名空间和方法名SoapObject soapObject = new SoapObject(PACE, M_NAME);// 创建SoapSerializationEnvelope对象并传入SOAP协议的版本号final SoapSerializationEnvelope soapserial = new SoapSerializationEnvelope(SoapEnvelope.VER11);soapserial.bodyOut = soapObject;// 设置与.NET提供的Web service保持有良好的兼容性soapserial.dotNet = true;// 使用Callable与Future来创建启动线程FutureTask<List<String>> future = new FutureTask<List<String>>(new Callable<List<String>>() {@Overridepublic List<String> call() throws Exception {List<String> citys = new ArrayList<String>();// 调用HttpTransportSE对象的call方法来调用 websericehttpSE.call(PACE + M_NAME, soapserial);if (soapserial.getResponse() != null) {// 获取服务器响应返回的SOAP消息SoapObject result = (SoapObject) soapserial.bodyIn;SoapObject detail = (SoapObject) result.getProperty("getSupportProvinceResult");// 解析返回信息for (int i = 0; i < detail.getPropertyCount(); i++) {citys.add(detail.getProperty(i).toString());}return citys;}return null;}});new Thread(future).start();try {return future.get();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}/** *  * @param citys *            省份 * @return 该省下的所有城市 */public static List<String> getCity(String citys) {// 创建HttpTransportSE对象final HttpTransportSE httpSE = new HttpTransportSE(SERVER_URL);httpSE.debug = true;// 创建SoapObject对象SoapObject soapObject = new SoapObject(PACE, MC_NAME);// 添加参数soapObject.addProperty("byProvinceName ", citys);// 创建SoapSerializationEnvelopefinal SoapSerializationEnvelope serializa = new SoapSerializationEnvelope(SoapEnvelope.VER11);serializa.bodyOut = soapObject;serializa.dotNet = true;FutureTask<List<String>> future = new FutureTask<List<String>>(new Callable<List<String>>() {@Overridepublic List<String> call() throws Exception {List<String> city = new ArrayList<String>();// 调用Web ServicehttpSE.call(PACE + MC_NAME, serializa);// 获取返回信息if (serializa.getResponse() != null) {SoapObject restul = (SoapObject) serializa.bodyIn;SoapObject detial = (SoapObject) restul.getProperty("getSupportCityResult");// 解析返回信息for (int i = 0; i < detial.getPropertyCount(); i++) {// 获取城市名String str = detial.getPropertyAsString(i).toString();String strCity = str.substring(0,str.indexOf("(") - 1);city.add(strCity);}return city;}return null;}});new Thread(future).start();try {return future.get();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}// 获取三天之内的天气详情public static List<String> getWeather(String citys) {final HttpTransportSE httpSe = new HttpTransportSE(SERVER_URL);httpSe.debug = true;SoapObject soapObject = new SoapObject(PACE, W_NAME);soapObject.addProperty("theCityName", citys);final SoapSerializationEnvelope serializa = new SoapSerializationEnvelope(SoapEnvelope.VER11);serializa.bodyOut = soapObject;serializa.dotNet = true;FutureTask<List<String>> future = new FutureTask<List<String>>(new Callable<List<String>>() {@Overridepublic List<String> call() throws Exception {List<String> list = new ArrayList<String>();// 调用webservicehttpSe.call(PACE+W_NAME, serializa);// 获取返回信息if (serializa.getResponse() != null) {SoapObject result = (SoapObject) serializa.bodyIn;SoapObject deialt = (SoapObject) result.getProperty("getWeatherbyCityNameResult");// 解析数据for (int i = 0; i < deialt.getPropertyCount(); i++) {list.add(deialt.getProperty(i).toString());}}return list;}});new Thread(future).start();try {return future.get();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}}

ChangeImageView.java

package com.example.webserviceteset;public class ChangeImageView {// 由于下载下来的图片分 大中小 三种 而调用远程webserivce获取的值是小的图片名 所以的 根据获取的图片名称来获取向对应的大图片IDpublic static int imageId(String ids) {int id = R.drawable.a_0;int ided =Integer.parseInt(ids.substring(0, ids.indexOf(".")));switch (ided) {case 1:id = R.drawable.a_1;break;case 2:id = R.drawable.a_2;break;case 3:id = R.drawable.a_3;break;case 4:id = R.drawable.a_4;break;case 5:id = R.drawable.a_5;break;case 6:id = R.drawable.a_6;break;case 7:id = R.drawable.a_7;break;case 8:id = R.drawable.a_8;break;case 9:id = R.drawable.a_9;break;case 10:id = R.drawable.a_10;break;case 11:id = R.drawable.a_11;break;case 12:id = R.drawable.a_12;break;case 13:id = R.drawable.a_13;break;case 14:id = R.drawable.a_1;break;case 15:id = R.drawable.a_15;break;case 16:id = R.drawable.a_16;break;case 17:id = R.drawable.a_17;break;case 18:id = R.drawable.a_18;break;case 19:id = R.drawable.a_19;break;case 20:id = R.drawable.a_20;break;case 21:id = R.drawable.a_21;break;case 22:id = R.drawable.a_22;break;case 23:id = R.drawable.a_23;break;case 24:id = R.drawable.a_24;break;case 25:id = R.drawable.a_25;break;case 26:id = R.drawable.a_26;break;case 27:id = R.drawable.a_27;break;case 28:id = R.drawable.a_28;break;case 29:id = R.drawable.a_29;break;case 30:id = R.drawable.a_30;break;}return id;}}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity" >    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <Spinner            android:id="@+id/citys"            android:layout_width="match_parent"            android:layout_height="wrap_content" />        <Spinner            android:id="@+id/city"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    </LinearLayout>    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <TextView            android:id="@+id/cityNames1"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />        <ImageView            android:id="@+id/weateImage1"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />    </LinearLayout>    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <TextView            android:id="@+id/cityNames2"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />        <ImageView            android:id="@+id/weateImage2"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />    </LinearLayout>    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <TextView            android:id="@+id/cityNames3"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />        <ImageView            android:id="@+id/weateImage3"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />    </LinearLayout>    <LinearLayout        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal" >        <TextView            android:id="@+id/cityjie"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:lines="6" />    </LinearLayout></LinearLayout>AndroidManifest.xmlAndroidManifest.xml

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.webserviceteset"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="11"        android:targetSdkVersion="17" />    <uses-permission         android:name="android.permission.INTERNET"/>    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.webserviceteset.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

源代码下载的地址 http://download.csdn.net/detail/x605940745/6578575

更多相关文章

  1. Android,一个函数实现温度计
  2. Android(安卓)Toast cancel问题、源码分析和解决方案
  3. 开发问题及解决 java.lang.ClassCastException:android.widget.L
  4. android adb 命令实践
  5. Android(安卓)input处理机制(一)InputReader
  6. Andriod使用Intent实现拨号
  7. android知识杂记(一)
  8. Android(安卓)通过包名打开App的代码
  9. Android之——AIDL小结

随机推荐

  1. 提android 项目方案一个求感兴趣者加入
  2. 【Anroid】第9章 列表视图(1)--ListView相
  3. android studio 3.x 以上版本的Native JN
  4. 无Mac机IOS开发环境搭建手记
  5. android实时滤镜的效率问题
  6. android开发基础(Android Application Fun
  7. Android(安卓)WebView加载Chromium动态库
  8. Android Wear之android穿戴式设备应用开
  9. android中获取手机相机和相册可以传多张
  10. 什么是Android(安卓)系统。