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
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
Android之ksoap2-android详解与调用天气预报Webservice完整实例的更多相关文章
- Android开发之InstanceState详解
Android开发之InstanceState详解 本文介绍Android中关于Activity的两个神秘方法:onSaveInstanceState() 和 onRestoreInstanceS ...
- Android中Service(服务)详解
http://blog.csdn.net/ryantang03/article/details/7770939 Android中Service(服务)详解 标签: serviceandroidappl ...
- 给 Android 开发者的 RxJava 详解
我从去年开始使用 RxJava ,到现在一年多了.今年加入了 Flipboard 后,看到 Flipboard 的 Android 项目也在使用 RxJava ,并且使用的场景越来越多 .而最近这几个 ...
- Android中mesure过程详解
我们在编写layout的xml文件时会碰到layout_width和layout_height两个属性,对于这两个属性我们有三种选择:赋值成具体的数值,match_parent或者wrap_conte ...
- Android中Intent组件详解
Intent是不同组件之间相互通讯的纽带,封装了不同组件之间通讯的条件.Intent本身是定义为一个类别(Class),一个Intent对象表达一个目的(Goal)或期望(Expectation),叙 ...
- [转]ANDROID L——Material Design详解(动画篇)
转载请注明本文出自大苞米的博客(http://blog.csdn.net/a396901990),谢谢支持! 转自:http://blog.csdn.net/a396901990/article/de ...
- Android开发之InstanceState详解(转)---利用其保存Activity状态
Android开发之InstanceState详解 本文介绍Android中关于Activity的两个神秘方法:onSaveInstanceState() 和 onRestoreInstanceS ...
- Android的init过程详解(一)
Android的init过程详解(一) Android的init过程(二):初始化语言(init.rc)解析 本文使用的软件版本 Android:4.2.2 Linux内核:3.1.10 本文及后续几 ...
- Android事件传递机制详解及最新源码分析——ViewGroup篇
版权声明:本文出自汪磊的博客,转载请务必注明出处. 在上一篇<Android事件传递机制详解及最新源码分析--View篇>中,详细讲解了View事件的传递机制,没掌握或者掌握不扎实的小伙伴 ...
随机推荐
- HDU4099(斐波那契数列与字典树)
题目:Revenge of Fibonacci 题意:给出斐波那契数列的前k位,k不超过40,找出最小的正整数n,满足F(n)的前k位与给定数的前k位相同,斐波那契数列的项数不超过100000. 解析 ...
- MVC3 验证码
public ActionResult GetValidateCode() { string code = CreateValidateC ...
- 「OC」内存管理
一.基本原理 (一)为什么要进行内存管理. 由于移动设备的内存极其有限,所以每个APP所占的内存也是有限制的,当app所占用的内存较多时,系统就会发出内存警告,这时需要回收一些不需要再继续使用的内存空 ...
- jacksonall的使用,解析json
转自:http://www.cnblogs.com/lee0oo0/archive/2012/08/23/2652751.html , Jackson可以轻松的将Java对象转换成json对象和xml ...
- php 自己写的好看的分页类
自己写的一个分页类 ,不是很完整,个别没有做验证,但可以使用,分页效果见文章底部.除了链接数据库的代码没有粘贴上来,其他的都粘贴了.供学习使用- <?php /** * Created by P ...
- css基本框架
- AnyEvent::HTTP 介绍
AnyEvent::HTTP - simple but non-blocking HTTP/HTTPS client 一个简单的非堵塞的 HTTP/HTTPS 客户端: use AnyEvent::H ...
- Java for循环用法
Java中for循环多了一种写法--foreach写法(一般仅仅用于遍历整个数组,不用操心越界等问题). 1.1)常规写法: package foreach.main.sn; public class ...
- Java中Volatile的作用
Java中Volatile的作用 看了几篇博客,发现没搞懂.可是简单来说,就是在我们的多线程开发中.我们用Volatile关键字来限定某个变量或者属性时,线程在每次使用变量的时候.都会读取变量改动后的 ...
- android CircularSeekBar
Android 中的 seekBar会被开发者经常用到,用的最多的空拍是控制音量.但是有时后为了更好的UI效果,横着的拖动条不能满足我们项目的需要,我们可能需要竖直的或者圆形的拖动条,那这两种样式的类 ...