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事件的传递机制,没掌握或者掌握不扎实的小伙伴 ...
随机推荐
- 前端性能监控系统ShowSlow
作者:zhanhailiang 日期:2014-11-14 1. 简单介绍 ShowSlow是开源的前端性能监控系统,提供了下面功能: 前端性能指标数据收集功能:ShowSlow原生提供了数据收集工具 ...
- Lamd表达式
1. 普通绑定: public void button1_Click(object sender, EventArgs e) { MessageBox.Show("ok"); } ...
- React Native-目前最火的前端技术?
做为一名产品经理,你是否遇到过这样的窘境,“帮我把字体调成 16号呗,颜色变成 #FFFF00FF,老大说这里最好改一下”,作为一名 app 的开发只能无奈但心里窃喜的告诉你,“只能等下个版本了,必须 ...
- 条款21: 必须返回对象时,不要强行返回对象的reference
总结: 绝不要返回一个local栈对象的指针或引用:绝不要返回一个被分配的堆对象的引用:绝不要返回一个静态局部对象(为了它,有可能同时需要多个这样的对象的指针或引用). 条款4中给出了“在单线程环境中 ...
- Oracle/Mysql批量插入的sql,效率比较高
1.oracle 批量插入: insert into tableName(col1,col2,col3...) select 1,'第一行第一列值','第二列值' from dual union ...
- Dojo实现Tabs页报错(三)
用Dojo实现tab页的过程中,没有引用“on.js”,但是firebug调试时一直提示如下错误: on.js源码如下: define(["./has!dom-addeventlistene ...
- 查看Oracle有哪些表或者视图
转自:http://www.2cto.com/database/201211/167577.html 1.查询当前用户下,有哪些表 Sql代码 SELECT * FROM user_tables ...
- selenium+BeautifulSoup+phantomjs爬取新浪新闻
一 下载phantomjs,把phantomjs.exe的文件路径加到环境变量中,也可以phantomjs.exe拷贝到一个已存在的环境变量路径中,比如我用的anaconda,我把phantomjs. ...
- mysql里的sql函数
仅作为自己忘记时的查询 时间 now() 返回当前年-月-日 时:分:秒格式的时间 UNIX_TIMESTAMP() 当前的uninx时间戳 date_format(date,格式) date是年月日 ...
- 关于64位Windows7系统下INF的安装问题
原文 http://bbs.csdn.net/topics/360262492 我的电脑 ——>属性 ——>设备管理器 ——>操作 ——>添加过时硬件 但是,64位系统上报“指 ...