上一节中我们通过http协议,采用HttpClient向服务器端action请求数据。当然调用服务器端方法获取数据并不止这一种。WebService也可以为我们提供所需数据,那么什么是webService呢?,它是一种基于SAOP协议的远程调用标准,通过webservice可以将不同操作系统平台,不同语言,不同技术整合到一起。

  我们在PC机器java客户端中,需要一些库,比如XFire,Axis2,CXF等等来支持访问WebService,但是这些库并不适合我们资源有限的android手机客户端,做过JAVA ME的人都知道有KSOAP这个第三方的类库,可以帮助我们获取服务器端webService调用,当然KSOAP已经提供了基于android版本的jar包了,那么我们就开始吧:

  首先下载KSOAP包:ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar包

  然后新建android项目:并把下载的KSOAP包放在android项目的lib目录下:右键->build path->configure build path--选择Libraries,如图:

  以下分为七个步骤来调用WebService方法:

  第一:实例化SoapObject 对象,指定webService的命名空间(从相关WSDL文档中可以查看命名空间),以及调用方法名称。如:

//命名空间
private static final String serviceNameSpace="http://WebXml.com.cn/";
//调用方法(获得支持的城市)
private static final String getSupportCity="getSupportCity";

//实例化SoapObject对象
SoapObject request=new SoapObject(serviceNameSpace, getSupportCity);

第二步:假设方法有参数的话,设置调用方法参数:

request.addProperty("参数名称","参数值");

  第三步:设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致):

//获得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;

  第四步:注册Envelope:

(new MarshalBase64()).register(envelope);

  第五步:构建传输对象,并指明WSDL文档URL:

//请求URL
private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//Android传输对象
AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
transport.debug=true;

  第六步:调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象):

transport.call(serviceNameSpace+getWeatherbyCityName, envelope);

  第七步:解析返回数据:

if(envelope.getResponse()!=null){
return parse(envelope.bodyIn.toString());
}
/**************
* 解析XML
* @param str
* @return
*/
private static List<String> parse(String str){
String temp;
List<String> list=new ArrayList<String>();
if(str!=null && str.length()>0){
int start=str.indexOf("string");
int end=str.lastIndexOf(";");
temp=str.substring(start, end-3);
String []test=temp.split(";");

for(int i=0;i<test.length;i++){
if(i==0){
temp=test[i].substring(7);
}else{
temp=test[i].substring(8);
}
int index=temp.indexOf(",");
list.add(temp.substring(0, index));
}
}
return list;
}

  这样就成功啦。那么现在我们就来测试下吧,这里有个地址提供webService天气预报的服务的,我这里只提供获取城市列表:

//命名空间
private static final String serviceNameSpace="http://WebXml.com.cn/";
//请求URL
private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//调用方法(获得支持的城市)
private static final String getSupportCity="getSupportCity";
//调用城市的方法(需要带参数)
private static final String getWeatherbyCityName="getWeatherbyCityName";
//调用省或者直辖市的方法(获得支持的省份或直辖市)
private static final String getSupportProvince="getSupportProvince";

  然后你可以在浏览器中输入地址(WSDL):serviceURL,你会看到一些可供调用的方法:

  我们选择获取国内外主要城市或者省份的方法吧:getSupportProvice,然后调用,你会发现浏览器返回给我们的是xml文档:

<?xml version="1.0" encoding="utf-8" ?>
- <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://WebXml.com.cn/">
<string>直辖市</string>
<string>特别行政区</string>
<string>黑龙江</string>
<string>吉林</string>
<string>辽宁</string>
<string>内蒙古</string>
<string>河北</string>
<string>河南</string>
<string>山东</string>
<string>山西</string>
<string>江苏</string>
<string>安徽</string>
<string>陕西</string>
<string>宁夏</string>
<string>甘肃</string>
<string>青海</string>
<string>湖北</string>
<string>湖南</string>
<string>浙江</string>
<string>江西</string>
<string>福建</string>
<string>贵州</string>
<string>四川</string>
<string>广东</string>
<string>广西</string>
<string>云南</string>
<string>海南</string>
<string>新疆</string>
<string>西藏</string>
<string>台湾</string>
<string>亚洲</string>
<string>欧洲</string>
<string>非洲</string>
<string>北美洲</string>
<string>南美洲</string>
<string>大洋洲</string>
</ArrayOfString>

  我们可以用 listview来显示:

  那么下面我将给出全部代码:

public class WebServiceHelper {

//WSDL文档中的命名空间
private static final String targetNameSpace="http://WebXml.com.cn/";
//WSDL文档中的URL
private static final String WSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";

//需要调用的方法名(获得本天气预报Web Services支持的洲、国内外省份和城市信息)
private static final String getSupportProvince="getSupportProvince";
//需要调用的方法名(获得本天气预报Web Services支持的城市信息,根据省份查询城市集合:带参数)
private static final String getSupportCity="getSupportCity";
//根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数
private static final String getWeatherbyCityName="getWeatherbyCityName";

/********
* 获得州,国内外省份和城市信息
* @return
*/
public List<String> getProvince(){
List<String> provinces=new ArrayList<String>();
String str="";
SoapObject soapObject=new SoapObject(targetNameSpace,getSupportProvince);
//request.addProperty("参数", "参数值");调用的方法参数与参数值(根据具体需要可选可不选)

SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;

AndroidHttpTransport httpTranstation=new AndroidHttpTransport(WSDL);
//或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
try {

httpTranstation.call(targetNameSpace+getSupportProvince, envelope);
SoapObject result=(SoapObject)envelope.getResponse();
//下面对结果进行解析,结构类似json对象
//str=(String) result.getProperty(6).toString();

int count=result.getPropertyCount();
for(int index=0;index<count;index++){
provinces.add(result.getProperty(index).toString());
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return provinces;
}

/**********
* 根据省份或者直辖市获取天气预报所支持的城市集合
* @param province
* @return
*/
public List<String> getCitys(String province){
List<String> citys=new ArrayList<String>();
SoapObject soapObject=new SoapObject(targetNameSpace,getSupportCity);
soapObject.addProperty("byProvinceName", province);
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(soapObject);

AndroidHttpTransport httpTransport=new AndroidHttpTransport(WSDL);
try {
httpTransport.call(targetNameSpace+getSupportCity, envelope);
SoapObject result=(SoapObject)envelope.getResponse();
int count=result.getPropertyCount();
for(int index=0;index<count;index++){
citys.add(result.getProperty(index).toString());
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return citys;
}

/***************************
* 根据城市信息获取天气预报信息
* @param city
* @return
***************************/
public WeatherBean getWeatherByCity(String city){

WeatherBean bean=new WeatherBean();

SoapObject soapObject=new SoapObject(targetNameSpace,getWeatherbyCityName);
soapObject.addProperty("theCityName",city);//调用的方法参数与参数值(根据具体需要可选可不选)

SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(soapObject);//envelope.bodyOut=request;

AndroidHttpTransport httpTranstation=new AndroidHttpTransport(WSDL);
//或者HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
try {
httpTranstation.call(targetNameSpace+getWeatherbyCityName, envelope);
SoapObject result=(SoapObject)envelope.getResponse();
//下面对结果进行解析,结构类似json对象
bean=parserWeather(result);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bean;
}

/**
* 解析返回的结果
* @param soapObject
*/
protected WeatherBean parserWeather(SoapObject soapObject){
WeatherBean bean=new WeatherBean();

List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();

Map<String,Object> map=new HashMap<String,Object>();

//城市名
bean.setCityName(soapObject.getProperty(1).toString());
//城市简介
bean.setCityDescription(soapObject.getProperty(soapObject.getPropertyCount()-1).toString());
//天气实况+建议
bean.setLiveWeather(soapObject.getProperty(10).toString()+"\n"+soapObject.getProperty(11).toString());

//其他数据
//日期,
String date=soapObject.getProperty(6).toString();
//---------------------------------------------------
String weatherToday="今天:" + date.split(" ")[0];
weatherToday+="\n天气:"+ date.split(" ")[1];
weatherToday+="\n气温:"+soapObject.getProperty(5).toString();
weatherToday+="\n风力:"+soapObject.getProperty(7).toString();
weatherToday+="\n";

List<Integer> icons=new ArrayList<Integer>();

icons.add(parseIcon(soapObject.getProperty(8).toString()));
icons.add(parseIcon(soapObject.getProperty(9).toString()));

map.put("weatherDay", weatherToday);
map.put("icons",icons);
list.add(map);

//-------------------------------------------------
map=new HashMap<String,Object>();
date=soapObject.getProperty(13).toString();
String weatherTomorrow="明天:" + date.split(" ")[0];
weatherTomorrow+="\n天气:"+ date.split(" ")[1];
weatherTomorrow+="\n气温:"+soapObject.getProperty(12).toString();
weatherTomorrow+="\n风力:"+soapObject.getProperty(14).toString();
weatherTomorrow+="\n";

icons=new ArrayList<Integer>();

icons.add(parseIcon(soapObject.getProperty(15).toString()));
icons.add(parseIcon(soapObject.getProperty(16).toString()));

map.put("weatherDay", weatherTomorrow);
map.put("icons",icons);
list.add(map);
//--------------------------------------------------------------
map=new HashMap<String,Object>();

date=soapObject.getProperty(18).toString();
String weatherAfterTomorrow="后天:" + date.split(" ")[0];
weatherAfterTomorrow+="\n天气:"+ date.split(" ")[1];
weatherAfterTomorrow+="\n气温:"+soapObject.getProperty(17).toString();
weatherAfterTomorrow+="\n风力:"+soapObject.getProperty(19).toString();
weatherAfterTomorrow+="\n";

icons=new ArrayList<Integer>();
icons.add(parseIcon(soapObject.getProperty(20).toString()));
icons.add(parseIcon(soapObject.getProperty(21).toString()));

map.put("weatherDay", weatherAfterTomorrow);
map.put("icons",icons);
list.add(map);
//--------------------------------------------------------------

bean.setList(list);
return bean;
}

//解析图标字符串
private int parseIcon(String data){
// 0.gif,返回名称0,
int resID=32;
String result=data.substring(0, data.length()-4).trim();
// String []icon=data.split(".");
// String result=icon[0].trim();
// Log.e("this is the icon", result.trim());

if(!result.equals("nothing")){
resID=Integer.parseInt(result.trim());
}
return resID;
//return ("a_"+data).split(".")[0];
}
}

  以及帮助类:

public class WebServiceUtil {

//命名空间
private static final String serviceNameSpace="http://WebXml.com.cn/";
//请求URL
private static final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//调用方法(获得支持的城市)
private static final String getSupportCity="getSupportCity";
//调用城市的方法(需要带参数)
private static final String getWeatherbyCityName="getWeatherbyCityName";
//调用省或者直辖市的方法(获得支持的省份或直辖市)
private static final String getSupportProvince="getSupportProvince";

/*************
* @return城市列表
*************/
public static List<String> getCityList(){
//实例化SoapObject对象
SoapObject request=new SoapObject(serviceNameSpace, getSupportCity);
//获得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
(new MarshalBase64()).register(envelope);
//Android传输对象
AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
transport.debug=true;

//调用
try {
transport.call(serviceNameSpace+getWeatherbyCityName, envelope);
if(envelope.getResponse()!=null){
return parse(envelope.bodyIn.toString());
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}

public static List<String> getProviceList(){
//实例化SoapObject对象
SoapObject request=new SoapObject(serviceNameSpace, getSupportProvince);
//获得序列化的Envelope
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
(new MarshalBase64()).register(envelope);
//Android传输对象
AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
transport.debug=true;

//调用
try {
transport.call(serviceNameSpace+getWeatherbyCityName, envelope);
if(envelope.getResponse()!=null){
return null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

/*************
* @param cityName
* @return
*************/
public static String getWeather(String cityName){

return "";
}

/**************
* 解析XML
* @param str
* @return
*/
private static List<String> parse(String str){
String temp;
List<String> list=new ArrayList<String>();
if(str!=null && str.length()>0){
int start=str.indexOf("string");
int end=str.lastIndexOf(";");
temp=str.substring(start, end-3);
String []test=temp.split(";");

for(int i=0;i<test.length;i++){
if(i==0){
temp=test[i].substring(7);
}else{
temp=test[i].substring(8);
}
int index=temp.indexOf(",");
list.add(temp.substring(0, index));
}
}
return list;
}

/*********
* 获取天气
* @param soapObject
*/
private void parseWeather(SoapObject soapObject){
//String date=soapObject.getProperty(6);
}
}

  以上就是我所作的查询天气预报的全部核心代码了,读者可以根据注释以及本文章了解下具体实现,相信很快就搞明白了,运行结果如下:

  到此结束,下一节主要是socket通信了。

http://kb.cnblogs.com/page/98804/

转载于:https://www.cnblogs.com/softidea/p/4783909.html

Android与服务器端数据交互(转)相关推荐

  1. Android与服务器端数据交互(基于SOAP协议整合android+webservice)

    转自:http://www.cnblogs.com/zhangdongzi/archive/2011/04/19/2020688.html 上一节中我们通过http协议,采用HttpClient向服务 ...

  2. Android与服务器端数据交互(基于SAOP协议整合android+webservice)

    上一节中我们通过http协议,采用HttpClient向服务器端action请求数据.当然调用服务器端方法获取数据并不止这一种.WebService也可以为我们提供所需数据, 那么什么是webSer ...

  3. app传输数据到php,安卓app客户端和使用php的服务器端数据交互

    php擅长网页开发,对http协议支持很好,如果采用php作为服务器的后台开发语言和安卓客户端进行数据交互,使封装了http协议的httpclient这个jar包,可以轻松进行数据交互,不需要了解ht ...

  4. android与tomcat数据交互

    绪论: 目前大部分android的APP都具有联网功能,并且能够与服务器进行数据交互,本文采用tomcat作为服务器以实现数据交互,信息交互的前提是android设备和服务器在同一个局域网内. and ...

  5. 安卓连接mysql客户端_安卓客户端与mysql服务器端数据交互

    1.安卓客户端的配置(上传数据) package com.dlvtc.upphp; import java.io.IOException; import java.io.UnsupportedEnco ...

  6. Android Studio 与 Tomcat 交互案例(新)

    首先默认已经装了Tomcat了,这方面的教程网上一大堆. github地址 文章目录 两数求和 账户登录与注册 两数求和 参考android与tomcat数据交互所写 移动端输入两个数,点击按钮,在w ...

  7. Android 客户端与服务器端进行数据交互(一、登录服务器端)

    概要 安卓APP要实现很多功能(比如登录注册.发表评论等)时都必须要使用到网络数据交互.所以在学习了这部分内容后,就将其以最常见的登录过程为例整理出来,也方便跟我一样的新手能迅速学习上手. 预期效果图 ...

  8. Android开发之Service与Activity数据交互(源代码分享)

    Service想要与Activity进行数据交互,首先Activity先得绑定Service.bound service是service 的实现,它允许其他应用程序绑定到它并与之交互.要提供bound ...

  9. Android开发之Fragment与Activity的数据交互通过回调机制实现(源代码分享)

    上一篇文章简单介绍了Android的回调机制的使用,这一篇博文将重点介绍Fragment碎片与activity的数据交互,fragment在Android开发中起着至关重要的作用,通过官方Androi ...

最新文章

  1. CCF大数据专家委:2018年大数据发展趋势预测
  2. 第215天:Angular---指令
  3. ue4sky时间_UE4 SkyLight RealTimeCapture浅析
  4. 如何使用SAP Gigya的登录服务和您的网站集成
  5. 聚类算法:K-Means
  6. delphi 执行长时间存储过程 显示进度_项目管理_十大管理体系之「项目进度管理」知识整理及心得分享...
  7. 测试库的接收到的数据是否完整(jrtplib为列)
  8. IplImage 封装释放
  9. “21天好习惯”第一期-18
  10. 如何用tomcat发布自己的Java项目
  11. SQL Server 2019 安装教程(详细免费,自定义安装)
  12. 无形资产计算机软件包括哪些,什么软件属于无形资产
  13. ARM926EJ-S/ARM920T 协处理器 CP14, CP15详解(转载)
  14. python图像光谱视觉分析库-imgvision
  15. matlab股票分析系统,matlab股票预测系统,matlab股票决策
  16. 安卓键盘加上数字_安卓键盘键值对照表
  17. Linux请求调页技术,linux零页技术.doc
  18. 算法-斐波那契数列 java
  19. Jsp网页中全角空格和半角空格放入区别
  20. 华生详解万科董事会:我为什么不支持大股东意见(中)

热门文章

  1. 如何在三个月学习三年的生活经验
  2. jboss-as-web-7.0.1.Final 配置 SSL
  3. ObjectDataSource未能找到带参数的非泛型方法的解决
  4. Base62x比Base64的编码速度更快吗?
  5. 【读书笔记】《高性能JavaScript》
  6. Mockplus设计大赛获奖选手专访 | High音:轻松生活,随心嗨音
  7. macbook和 windows共享文件
  8. 利用 GPU 加速人工智能:新型计算模式
  9. Spring 教程(三) 环境设置
  10. Eclipse下配置主题颜色