Android之ksoap2-android详解与调用天气预报Webservice完整实例

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

使用 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

Android之ksoap2-android详解与调用天气预报Webservice完整实例

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;



	@Override

	protected 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() {



			@Override

			public 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);



			}



			@Override

			public void onNothingSelected(AdapterView<?> arg0) {

				// TODO Auto-generated method stub



			}

		});

		city.setOnItemSelectedListener(new OnItemSelectedListener() {

			// 返回数据: 一个一维数组 String(22),共有23个元素。

			@Override

			public 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));

				

				

			}



			@Override

			public void onNothingSelected(AdapterView<?> arg0) {

				// TODO Auto-generated method stub



			}

		});



	}



	@Override

	public 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>>() {

					@Override

					public List<String> call() throws Exception {

						List<String> citys = new ArrayList<String>();

						// 调用HttpTransportSE对象的call方法来调用 webserice

						httpSE.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 block

			e.printStackTrace();

		} catch (ExecutionException e) {

			// TODO Auto-generated catch block

			e.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);

		// 创建SoapSerializationEnvelope

		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>>() {



					@Override

					public List<String> call() throws Exception {

						List<String> city = new ArrayList<String>();

						// 调用Web Service

						httpSE.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 block

			e.printStackTrace();

		} catch (ExecutionException e) {

			// TODO Auto-generated catch block

			e.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>>() {

					@Override

					public List<String> call() throws Exception {

						List<String> list = new ArrayList<String>();

						// 调用webservice

						httpSe.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 block

			e.printStackTrace();

		} catch (ExecutionException e) {

			// TODO Auto-generated catch block

			e.printStackTrace();

		}

		return null;

	}



}

ChangeImageView.java

package com.example.webserviceteset;



public class ChangeImageView {

	// 由于下载下来的图片分 大中小 三种 而调用远程webserivce获取的值是小的图片名 所以的 根据获取的图片名称来获取向对应的大图片ID

	public 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

你可能感兴趣的:(webservice)