Android:WebService
Android:WebService使用实例
分类:Android 2013-09-23 14:48 6156人阅读 评论(14) 收藏 举报最近刚刚开始学习使用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,如图:
同时,只添加jar包肯能是不够的,需要添加class folder,即可以再工程的libs文件夹中加入下载的KSOAP包,如图:
环境配好之后可以用下面七个步骤来调用WebService方法:
第一:实例化SoapObject对象,指定webService的命名空间(从相关WSDL文档中可以查看命名空间),以及调用方法名称。如:
//命名空间
privatestaticfinal String serviceNameSpace="http://WebXml.com.cn/";
//调用方法(获得支持的城市)
privatestaticfinal String getSupportCity="getSupportCity";
//实例化SoapObject对象
SoapObject request=newSoapObject(serviceNameSpace, getSupportCity);
第二步:假设方法有参数的话,设置调用方法参数:
request.addProperty("参数名称","参数值");
第三步:设置SOAP请求信息(参数部分为SOAP协议版本号,与你要调用的webService中版本号一致):
//获得序列化的Envelope
SoapSerializationEnvelope envelope=newSoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
第四步:注册Envelope:
(newMarshalBase64()).register(envelope);
第五步:构建传输对象,并指明WSDL文档URL:
//请求URL
privatestaticfinal String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//Android传输对象
AndroidHttpTransport transport=newAndroidHttpTransport(serviceURL);
transport.debug=true;
第六步:调用WebService(其中参数为1:命名空间+方法名称,2:Envelope对象):
transport.call(serviceNameSpace+getWeatherbyCityName, envelope);
第七步:解析返回数据:
if(envelope.getResponse()!=null){
returnparse(envelope.bodyIn.toString());
}
这里有个地址提供webService天气预报的服务网站,在浏览器中输入网站:http://www.webxml.com.cn/webservices/weatherwebservice.asmx可以看到该网站提供的
调用方法,点进去之后可以看到调用时需要输入的参数,当然有的不需要参数,例如:getSupportProvince,而getSupportCity需要输入查找的省份名,getWeatherbyCityName需要输入查找的城市名。接下来我们就利用这三个接口获得数据,并做出显示:
获得本天气预报Web Service支持的洲,国内外省份和城市信息:
[html] view plain copy print ?- publicclassMainActivityextendsActivity{
- //WSDL文档中的命名空间
- privatestaticfinalStringtargetNameSpace="http://WebXml.com.cn/";
- //WSDL文档中的URL
- privatestaticfinalStringWSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
- //需要调用的方法名(获得本天气预报WebServices支持的洲、国内外省份和城市信息)
- privatestaticfinalStringgetSupportProvince="getSupportProvince";
- privateList<Map<String,String>>listItems;
- privateListViewmListView;
- @Override
- protectedvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- listItems=newArrayList<Map<String,String>>();
- mListView=(ListView)findViewById(R.id.province_list);
- newNetAsyncTask().execute();
- mListView.setOnItemClickListener(newAdapterView.OnItemClickListener(){
- @Override
- publicvoidonItemClick(AdapterView<?>parent,Viewview,
- intposition,longid){
- StringmProvinceName=listItems.get(position).get("province");
- Log.d("ProvinceName",mProvinceName);
- Intentintent=newIntent();
- intent.putExtra("Pname",mProvinceName);
- intent.setClass(MainActivity.this,CityActivity.class);
- startActivity(intent);
- }
- });
- }
- classNetAsyncTaskextendsAsyncTask<Object,Object,String>{
- @Override
- protectedvoidonPostExecute(Stringresult){
- if(result.equals("success")){
- //列表适配器
- SimpleAdaptersimpleAdapter=newSimpleAdapter(MainActivity.this,listItems,R.layout.province_item,
- newString[]{"province"},newint[]{R.id.province});
- mListView.setAdapter(simpleAdapter);
- }
- super.onPostExecute(result);
- }
- @Override
- protectedStringdoInBackground(Object...params){
- //根据命名空间和方法得到SoapObject对象
- SoapObjectsoapObject=newSoapObject(targetNameSpace,
- getSupportProvince);
- //通过SOAP1.1协议得到envelop对象
- SoapSerializationEnvelopeenvelop=newSoapSerializationEnvelope(
- SoapEnvelope.VER11);
- //将soapObject对象设置为envelop对象,传出消息
- envelop.dotNet=true;
- envelop.setOutputSoapObject(soapObject);
- //或者envelop.bodyOut=soapObject;
- HttpTransportSEhttpSE=newHttpTransportSE(WSDL);
- //开始调用远程方法
- try{
- httpSE.call(targetNameSpace+getSupportProvince,envelop);
- //得到远程方法返回的SOAP对象
- SoapObjectresultObj=(SoapObject)envelop.getResponse();
- //得到服务器传回的数据
- intcount=resultObj.getPropertyCount();
- for(inti=0;i<count;i++){
- Map<String,String>listItem=newHashMap<String,String>();
- listItem.put("province",resultObj.getProperty(i).toString());
- listItems.add(listItem);
- }
- }catch(IOExceptione){
- e.printStackTrace();
- return"IOException";
- }catch(XmlPullParserExceptione){
- e.printStackTrace();
- return"XmlPullParserException";
- }
- return"success";
- }
- }
- }
显示省份列表的activity_main.xml文件:
[html] view plain copy print ?- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="match_parent">
- <ListView
- android:id="@+id/province_list"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"/>
- </LinearLayout>
列表中选项显示的province_item.xml文件:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <TextView
- android:id="@+id/province"
- android:layout_width="fill_parent"
- android:layout_height="match_parent"
- android:textSize="20sp"/>
- </LinearLayout>
效果图,如图:
查询本天气预报Web Services支持的国内外城市或地区信息:
[java] view plain copy print ?- publicclassCityActivityextendsActivity{
- //WSDL文档中的命名空间
- privatestaticfinalStringtargetNameSpace="http://WebXml.com.cn/";
- //WSDL文档中的URL
- privatestaticfinalStringWSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
- //需要调用的方法名(获得本天气预报WebServices支持的城市信息,根据省份查询城市集合:带参数)
- privatestaticfinalStringgetSupportCity="getSupportCity";
- privateList<Map<String,String>>listItems;
- privateListViewmListView;
- @Override
- protectedvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- listItems=newArrayList<Map<String,String>>();
- mListView=(ListView)findViewById(R.id.province_list);
- newNetAsyncTask().execute();
- //列表单击事件监听
- mListView.setOnItemClickListener(newAdapterView.OnItemClickListener(){
- @Override
- publicvoidonItemClick(AdapterView<?>parent,Viewview,
- intposition,longid){
- StringmCityName=listItems.get(position).get("city");
- StringcityName=getCityName(mCityName);
- Log.d("CityName",cityName);
- Intentintent=newIntent();
- //存储选择的城市名
- intent.putExtra("Cname",cityName);
- intent.setClass(CityActivity.this,WeatherActivity.class);
- startActivity(intent);
- }
- });
- }
- /**
- *拆分“城市(代码)”字符串,将“城市”字符串分离
- *@paramname
- *@return
- */
- publicStringgetCityName(Stringname){
- Stringcity="";
- intposition=name.indexOf('');
- city=name.substring(0,position);
- returncity;
- }
- classNetAsyncTaskextendsAsyncTask<Object,Object,String>{
- @Override
- protectedvoidonPostExecute(Stringresult){
- if(result.equals("success")){
- //列表适配器
- SimpleAdaptersimpleAdapter=newSimpleAdapter(CityActivity.this,listItems,R.layout.province_item,
- newString[]{"city"},newint[]{R.id.province});
- mListView.setAdapter(simpleAdapter);
- }
- super.onPostExecute(result);
- }
- @Override
- protectedStringdoInBackground(Object...params){
- //根据命名空间和方法得到SoapObject对象
- SoapObjectsoapObject=newSoapObject(targetNameSpace,getSupportCity);
- //参数输入
- Stringname=getIntent().getExtras().getString("Pname");
- soapObject.addProperty("byProvinceName",name);
- //通过SOAP1.1协议得到envelop对象
- SoapSerializationEnvelopeenvelop=newSoapSerializationEnvelope(
- SoapEnvelope.VER11);
- //将soapObject对象设置为envelop对象,传出消息
- envelop.dotNet=true;
- envelop.setOutputSoapObject(soapObject);
- HttpTransportSEhttpSE=newHttpTransportSE(WSDL);
- //开始调用远程方法
- try{
- httpSE.call(targetNameSpace+getSupportCity,envelop);
- //得到远程方法返回的SOAP对象
- SoapObjectresultObj=(SoapObject)envelop.getResponse();
- //得到服务器传回的数据
- intcount=resultObj.getPropertyCount();
- for(inti=0;i<count;i++){
- Map<String,String>listItem=newHashMap<String,String>();
- listItem.put("city",resultObj.getProperty(i).toString());
- listItems.add(listItem);
- }
- }catch(IOExceptione){
- e.printStackTrace();
- return"IOException";
- }catch(XmlPullParserExceptione){
- e.printStackTrace();
- return"XmlPullParserException";
- }
- return"success";
- }
- }
- }
用于列表显示的xml重复使用,这里就不再重复写一次了,效果图,如图:
最后,根据选择的城市或地区名称获得天气情况:
[java] view plain copy print ?- publicclassWeatherActivityextendsActivity{
- //WSDL文档中的命名空间
- privatestaticfinalStringtargetNameSpace="http://WebXml.com.cn/";
- //WSDL文档中的URL
- privatestaticfinalStringWSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
- //根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数
- privatestaticfinalStringgetWeatherbyCityName="getWeatherbyCityName";
- WeatherBeanmWBean;
- privateImageViewmImageView;
- privateEditTextmCityName;
- privateEditTextmTemp;
- privateEditTextmWeather;
- privateTextViewmToday;
- privateTextViewmDetail;
- privateintImage[];
- @Override
- protectedvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.weather);
- Image=newint[]{R.drawable.image0,R.drawable.image1,R.drawable.image2,
- R.drawable.image3,R.drawable.image4,R.drawable.image5,
- R.drawable.image6,R.drawable.image7,R.drawable.image8,
- R.drawable.image9,R.drawable.image10,R.drawable.image11,
- R.drawable.image12,R.drawable.image13,R.drawable.image14,
- R.drawable.image15,R.drawable.image16,R.drawable.image17,
- R.drawable.image18,R.drawable.image19,R.drawable.image20,
- R.drawable.image21,R.drawable.image22,R.drawable.image23,
- R.drawable.image24,R.drawable.image25,R.drawable.image26,
- R.drawable.image27};
- mWBean=newWeatherBean();
- mImageView=(ImageView)findViewById(R.id.picture);
- mCityName=(EditText)findViewById(R.id.city_name);
- mTemp=(EditText)findViewById(R.id.temp);
- mWeather=(EditText)findViewById(R.id.weather);
- mToday=(TextView)findViewById(R.id.today_weather);
- mDetail=(TextView)findViewById(R.id.city_detail);
- newNetAsyncTask().execute();
- }
- classNetAsyncTaskextendsAsyncTask<Object,Object,String>{
- @Override
- protectedvoidonPostExecute(Stringresult){
- Stringimage=mWBean.getWeatherPicture();
- intposition=getImageId(image);
- Log.d("image",Image[position]+"");
- mImageView.setImageResource(Image[position]);
- mCityName.setText(mWBean.getCityName());
- mTemp.setText(mWBean.getTemp());
- mWeather.setText(mWBean.getWeather());
- mToday.setText(mWBean.getLiveWeather());
- mDetail.setText(mWBean.getCityDetail());
- super.onPostExecute(result);
- }
- publicintgetImageId(Stringpicture){
- intid=0;
- inttempId=picture.indexOf('.');
- Stringsub=picture.substring(0,tempId);
- id=Integer.parseInt(sub);
- returnid;
- }
- @Override
- protectedStringdoInBackground(Object...params){
- //根据命名空间和方法得到SoapObject对象
- SoapObjectsoapObject=newSoapObject(targetNameSpace,getWeatherbyCityName);
- Stringcity=getIntent().getExtras().getString("Cname");
- soapObject.addProperty("theCityName",city);//调用的方法参数与参数值(根据具体需要可选可不选)
- //通过SOAP1.1协议得到envelop对象
- SoapSerializationEnvelopeenvelop=newSoapSerializationEnvelope(SoapEnvelope.VER11);
- //将soapObject对象设置为envelop对象,传出消息
- envelop.dotNet=true;
- envelop.setOutputSoapObject(soapObject);
- //或者envelop.bodyOut=soapObject;
- HttpTransportSEhttpSE=newHttpTransportSE(WSDL);
- //开始调用远程方法
- try{
- httpSE.call(targetNameSpace+getWeatherbyCityName,envelop);
- //得到远程方法返回的SOAP对象
- SoapObjectresultObj=(SoapObject)envelop.getResponse();
- //得到服务器传回的数据
- mWBean.setCityName(resultObj.getProperty(1).toString());
- mWBean.setTemp(resultObj.getProperty(5).toString());
- mWBean.setWeather(resultObj.getProperty(6).toString());
- mWBean.setWeatherPicture(resultObj.getProperty(8).toString());
- mWBean.setLiveWeather(resultObj.getProperty(10).toString());
- mWBean.setCityDetail(resultObj.getProperty(22).toString());
- }catch(IOExceptione){
- e.printStackTrace();
- return"IOException";
- }catch(XmlPullParserExceptione){
- e.printStackTrace();
- return"XmlPullParserException";
- }
- return"success";
- }
- }
- }
这里没有显示全部的信息,提供了一个存储部分天气信息的类:
- publicclassWeatherBean{
- privateStringCityName;
- privateStringTemp;
- privateStringWeather;
- privateStringWeatherPicture;
- privateStringLiveWeather;
- privateStringCityDetail;
- publicStringgetCityName(){
- returnCityName;
- }
- publicvoidsetCityName(StringcityName){
- CityName=cityName;
- }
- publicStringgetLiveWeather(){
- returnLiveWeather;
- }
- publicvoidsetLiveWeather(StringliveWeather){
- LiveWeather=liveWeather;
- }
- publicStringgetTemp(){
- returnTemp;
- }
- publicvoidsetTemp(Stringtemp){
- Temp=temp;
- }
- publicStringgetWeather(){
- returnWeather;
- }
- publicvoidsetWeather(Stringweather){
- Weather=weather;
- }
- publicStringgetWeatherPicture(){
- returnWeatherPicture;
- }
- publicvoidsetWeatherPicture(StringweatherPicture){
- WeatherPicture=weatherPicture;
- }
- publicStringgetCityDetail(){
- returnCityDetail;
- }
- publicvoidsetCityDetail(StringcityDetail){
- CityDetail=cityDetail;
- }
- }
显示天气状况的weather.xml文件:
[html] view plain copy print ?- <?xmlversion="1.0"encoding="utf-8"?>
- <ScrollViewxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical">
- <TableLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content">
- <TableRow>
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="天气实况:"
- android:textSize="16sp"/>
- <ImageView
- android:id="@+id/picture"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
- </TableRow>
- <TableRow>
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:text="城市:"
- android:textSize="16sp"/>
- <EditText
- android:id="@+id/city_name"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="2"
- android:hint="城市名称"
- android:editable="false"/>
- </TableRow>
- <TableRow>
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:text="温度:"
- android:textSize="16sp"/>
- <EditText
- android:id="@+id/temp"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="2"
- android:hint="今日气温"
- android:editable="false"/>
- </TableRow>
- <TableRow>
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:text="天气:"
- android:textSize="16sp"/>
- <EditText
- android:id="@+id/weather"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="2"
- android:hint="今日天气"
- android:editable="false"/>
- </TableRow>
- </TableLayout>
- <TextView
- android:id="@+id/today_weather"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:textSize="16sp"/>
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="城市简介:"
- android:textSize="16sp"/>
- <TextView
- android:id="@+id/city_detail"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:textSize="16sp"/>
- </LinearLayout>
- </ScrollView>
效果图如图:
这里许多功能做得不是很完善,大家可以根据自己的需要进行设计~
更多相关文章
- eclipse:打开 eclipse 出现 “android sdk content loader 0%”
- Android Service的使用方法 音乐播放器实例
- Android定制RadioButton样式三种实现方法
- android调用Webservice方法
- Android 文件读写操作方法总结
- 对android里布局文件当中的TextView对象设置事件监听,但是不响应
- 低版本android project在高版本ADK中运行方法
- Android中应用界面主题Theme使用方法和页面定时跳转应用