微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WebService使用实例

最近刚刚开始学习使用WebService的方法进行服务器端数据交互,发现网上的资料不是很全,

目前就结合收集到的一些资料做了一个小例子和大家分享一下~

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

首先下载包:ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar包      下载地址         点击进入代码下载

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

 

同时,只添加jar包肯能是不够的,需要添加class folder,即可以再工程的libs文件夹中加入下载的KSOAP包,如图:

  

 

环境配好之后可以用下面七个步骤来调用方法

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

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

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

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

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

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

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

第四步:注册Envelope (new MarshalBase64()).register(envelope);

第五步:构建传输对象,并指明文档URL //请求URL
privatestatic final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//Android传输对象
AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
transport.debug=true;

第六步:调用WebService(其中参数为1:命名空间+方法名称2对象 transport.call(serviceNameSpace+getWeatherbyCityName,envelope);

第七步:解析返回数据:

if(envelope.getResponse()!=null){
                return parse(envelope.bodyIn.toString());
            }

这里有个地址提供天气预报的服务网站,在浏览器中输入网站:http://www.webxml.com.cn/webservices/weatherwebservice.asmx可以看到该网站提供的

调用方法,点进去之后可以看到调用时需要输入的参数,当然有的不需要参数,例如:getSupportProvince ,而getSupportCity需要输入查找的省份名,getWeatherbyCityName 需要输入查找的城市名。接下来我们就利用这三个接口获得数据,并做出显示

获得本天气预报Web Service支持的洲,国内外省份和城市信息:

[html]  view plain copy print ?
  1. public class MainActivity extends Activity {  
  2.     // WSDL文档中的命名空间  
  3.     private static final String targetNameSpace = "http://WebXml.com.cn/";  
  4.     // WSDL文档中的URL  
  5.     private static final String WSDL = "http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";  
  6.   
  7.     // 需要调用方法名(获得本天气预报Web Services支持的洲、国内外省份和城市信息)  
  8.     private static final String getSupportProvince = "getSupportProvince";  
  9.     private List<Map<String,String>> listItems;  
  10.     private ListView mListView;  
  11.   
  12.     @Override  
  13.     protected void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.activity_main);  
  16.         listItems = new ArrayList<Map<String,String>>();  
  17.         mListView = (ListView) findViewById(R.id.province_list);  
  18.         new NetAsyncTask().execute();  
  19.         mListView.setonItemClickListener(new AdapterView.OnItemClickListener() {  
  20.             @Override  
  21.             public void onItemClick(AdapterView<?> parent, View view,  
  22.                     int position, long id) {  
  23.                 String mProvinceName = listItems.get(position).get("province");  
  24.                 Log.d("ProvinceName", mProvinceName);  
  25.                 Intent intent = new Intent();  
  26.                 intent.putExtra("Pname",85); line-height:18px">                 intent.setClass(MainActivity.this, CityActivity.class);  
  27.                 startActivity(intent);  
  28.             }  
  29.               
  30.         });  
  31.     }  
  32.     class NetAsyncTask extends AsyncTask<Object, Object, String> {  
  33.         @Override  
  34.         protected void onPostExecute(String result) {  
  35.             if (result.equals("success")) {  
  36.                 //列表适配器  
  37.                 SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this, listItems, R.layout.province_item,   
  38.                         new String[] {"province"}, new int[]{R.id.province});  
  39.                 mListView.setAdapter(simpleAdapter);  
  40.             super.onPostExecute(result);  
  41.         }  
  42.         @Override  
  43.         protected String doInBackground(Object... params) {  
  44.             // 根据命名空间和方法得到SoapObject对象  
  45.             SoapObject soapObject = new SoapObject(targetNameSpace,  
  46.                     getSupportProvince);  
  47.             // 通过SOAP1.1协议得到envelop对象  
  48.             SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(  
  49.                     SoapEnvelope.VER11);  
  50.             // 将soapObject对象设置为envelop对象,传出消息  
  51.             envelop.dotNet = true;  
  52.             envelop.setoutputSoapObject(soapObject);  
  53.             // 或者envelop.bodyOut = soapObject;  
  54.             HttpTransportSE httpSE = new HttpTransportSE(WSDL);  
  55.             // 开始调用远程方法  
  56.             try {  
  57.                 httpSE.call(targetNameSpace + getSupportProvince, envelop);  
  58.                 // 得到远程方法返回的SOAP对象  
  59.                 SoapObject resultObj = (SoapObject) envelop.getResponse();  
  60.                 // 得到服务器传回的数据  
  61.                 int count = resultObj.getPropertyCount();  
  62.                 for (int i = 0; i < count; i++) {  
  63.                     Map<String,String> listItem = new HashMap<String, String>();  
  64.                     listItem.put("province", resultObj.getProperty(i).toString());  
  65.                     listItems.add(listItem);  
  66.                 }  
  67.             } catch (IOException e) {  
  68.                 e.printstacktrace();  
  69.                 return "IOException";  
  70.             } catch (XmlPullParserException e) {  
  71.                 e.printstacktrace();  
  72.                 return "XmlPullParserException";  
  73.             return "success";  
  74. }  

显示省份列表的activity_main.xml文件

?
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  1.     android:layout_width="fill_parent"  
  2.     android:layout_height="match_parent" >  
  3.     <ListView   
  4.         android:id="@+id/province_list"  
  5.         android:layout_width="fill_parent"  
  6.         android:layout_height="fill_parent"/>  
  7. </LinearLayout>  


列表中选项显示的province_item.xml文件

?
    <?xml version="1.0" encoding="utf-8"?>  
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:orientation="vertical" >  
  5.       
  6.     <TextView   
  7.         android:id="@+id/province"  
  8.         android:layout_height="match_parent"  
  9.         android:textSize="20sp"/>  
  10. </LinearLayout>  


效果图,如图:

 

查询本天气预报Web Services支持的国内外城市或地区信息:

[java]  ?
    public class CityActivity extends Activity {  
  1.     // WSDL文档中的命名空间  
  2.     private static final String targetNameSpace = "http://WebXml.com.cn/";  
  3. // WSDL文档中的URL  
  4.     private static final String WSDL = "http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";  
  5.     // 需要调用方法名(获得本天气预报Web Services支持的城市信息,根据省份查询城市集合:带参数)  
  6.     private static final String getSupportCity = "getSupportCity";  
  7.     private List<Map<String,String>> listItems;  
  8.     private ListView mListView;  
  9.     @Override  
  10.     protected void onCreate(Bundle savedInstanceState) {  
  11.         super.onCreate(savedInstanceState);  
  12.         listItems = new ArrayList<Map<String,String>>();  
  13.         mListView = (ListView) findViewById(R.id.province_list);  
  14.         new NetAsyncTask().execute();  
  15.         //列表单击事件监听  
  16.         mListView.setonItemClickListener(new AdapterView.OnItemClickListener() {  
  17.                          public void onItemClick(AdapterView<?> parent,85); line-height:18px">                     int position, long id) {  
  18.                 String mCityName = listItems.get(position).get("city");  
  19.                 String cityName = getCityName(mCityName);  
  20.                 Log.d("CityName", cityName);  
  21.                 Intent intent = new Intent();  
  22.                 //存储选择的城市名  
  23.                 intent.putExtra("Cname", cityName);  
  24.                 intent.setClass(CityActivity.this, WeatherActivity.class);  
  25.                 startActivity(intent);  
  26.             }  
  27.               
  28.         });  
  29.     }  
  30. /** 
  31.      * 拆分“城市 (代码)”字符串,将“城市”字符串分离 
  32.      * @param name 
  33.      * @return 
  34.      */  
  35.     public String getCityName(String name) {  
  36.         String city = "";  
  37.         int position = name.indexOf(' ');  
  38.         city = name.substring(0, position);  
  39.         return city;  
  40.     class NetAsyncTask extends AsyncTask<Object, String> {  
  41.         @Override  
  42.         protected void onPostExecute(String result) {  
  43.             if (result.equals("success")) {  
  44.                 //列表适配器  
  45.                 SimpleAdapter simpleAdapter = new SimpleAdapter(CityActivity.this,85); line-height:18px">                         new String[] {"city"}, new int[]{R.id.province});  
  46.             super.onPostExecute(result);  
  47.                  protected String doInBackground(Object... params) {  
  48.             // 根据命名空间和方法得到SoapObject对象  
  49.             SoapObject soapObject = new SoapObject(targetNameSpace,getSupportCity);  
  50. //参数输入  
  51.             String name = getIntent().getExtras().getString("Pname");  
  52.             soapObject.addProperty("byProvinceName", name);  
  53.             // 通过SOAP1.1协议得到envelop对象  
  54.             SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(  
  55. // 将soapObject对象设置为envelop对象,传出消息  
  56.             envelop.dotNet = true;  
  57.             envelop.setoutputSoapObject(soapObject);  
  58.             HttpTransportSE httpSE = new HttpTransportSE(WSDL);  
  59. // 开始调用远程方法  
  60.             try {  
  61.                 httpSE.call(targetNameSpace + getSupportCity,0); background-color:inherit">// 得到远程方法返回的SOAP对象  
  62.                 SoapObject resultObj = (SoapObject) envelop.getResponse();  
  63. // 得到服务器传回的数据  
  64.                 int count = resultObj.getPropertyCount();  
  65.                 for (int i = 0; i < count; i++) {  
  66.                     Map<String,String> listItem = new HashMap<String, String>();  
  67.                     listItem.put("city", resultObj.getProperty(i).toString());  
  68.             } catch (IOException e) {  
  69.                 return "IOException";  
  70.             } catch (XmlPullParserException e) {  
  71.                 return "XmlPullParserException";  
  72.             return "success";  
  73. }  


用于列表显示的xml重复使用,这里就不再重复写一次了,效果图,如图:


最后,根据选择的城市或地区名称获得天气情况:

?
    public class WeatherActivity extends Activity {  
  1. //WSDL文档中的命名空间  
  2.     private static final String targetNameSpace="http://WebXml.com.cn/";  
  3. //WSDL文档中的URL  
  4.     private static final String WSDL="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";  
  5. //根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数  
  6.     private static final String getWeatherbyCityName="getWeatherbyCityName";  
  7.     WeatherBean mWBean;  
  8.     private ImageView mImageView;  
  9.     private EditText mCityName;  
  10.     private EditText mTemp;  
  11.     private EditText mWeather;  
  12.     private TextView mToday;  
  13.     private TextView mDetail;  
  14.     private int Image[];  
  15.          protected void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.weather);  
  18.         Image = new int[]{R.drawable.image0,R.drawable.image1,R.drawable.image2,85); line-height:18px">                 R.drawable.image3,R.drawable.image4,R.drawable.image5,  
  19.                 R.drawable.image6,R.drawable.image7,R.drawable.image8,  
  20.                 R.drawable.image9,R.drawable.image10,R.drawable.image11,226); color:inherit; line-height:18px">                 R.drawable.image12,R.drawable.image13,R.drawable.image14,85); line-height:18px">                 R.drawable.image15,R.drawable.image16,R.drawable.image17,226); color:inherit; line-height:18px">                 R.drawable.image18,R.drawable.image19,R.drawable.image20,85); line-height:18px">                 R.drawable.image21,R.drawable.image22,R.drawable.image23,226); color:inherit; line-height:18px">                 R.drawable.image24,R.drawable.image25,R.drawable.image26,85); line-height:18px">                 R.drawable.image27};  
  21.         mWBean = new WeatherBean();  
  22.         mImageView = (ImageView) findViewById(R.id.picture);  
  23.         mCityName = (EditText) findViewById(R.id.city_name);  
  24.         mTemp = (EditText) findViewById(R.id.temp);  
  25.         mWeather = (EditText) findViewById(R.id.weather);  
  26.         mToday = (TextView) findViewById(R.id.today_weather);  
  27.         mDetail = (TextView) findViewById(R.id.city_detail);  
  28.           
  29.       
  30.     class NetAsyncTask extends AsyncTask<Object, String> {  
  31.         protected void onPostExecute(String result) {  
  32.             String image = mWBean.getWeatherPicture();  
  33.             int position = getimageId(image);  
  34.             Log.d("image", Image[position]+"");  
  35.             mImageView.setimageResource(Image[position]);  
  36.             mCityName.setText(mWBean.getCityName());  
  37.             mTemp.setText(mWBean.getTemp());  
  38.             mWeather.setText(mWBean.getWeather());  
  39.             mToday.setText(mWBean.getLiveWeather());  
  40.             mDetail.setText(mWBean.getCityDetail());  
  41.         public int getimageId(String picture) {  
  42.             int id = 0;  
  43.             int tempId = picture.indexOf('.');  
  44.             String sub = picture.substring(             id = Integer.parseInt(sub);  
  45.             return id;  
  46.             String city = getIntent().getExtras().getString("Cname");  
  47.             soapObject.addProperty("theCityName",city);//调用方法参数与参数值(根据具体需要可选可不选)  
  48. // 通过SOAP1.1协议得到envelop对象  
  49.             SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);  
  50.             envelop.dotNet = true;  
  51. // 或者envelop.bodyOut = soapObject;  
  52.                 httpSE.call(targetNameSpace + getWeatherbyCityName,85); line-height:18px">                 mWBean.setCityName(resultObj.getProperty(1).toString());  
  53.                 mWBean.setTemp(resultObj.getProperty(5).toString());  
  54.                 mWBean.setWeather(resultObj.getProperty(6).toString());  
  55.                 mWBean.setWeatherPicture(resultObj.getProperty(8).toString());  
  56.                 mWBean.setLiveWeather(resultObj.getProperty(10).toString());  
  57.                 mWBean.setCityDetail(resultObj.getProperty(22).toString());  
  58.                   
  59.             } catch (IOException e) {  
  60.                 return "IOException";  
  61.             } catch (XmlPullParserException e) {  
  62.                 return "XmlPullParserException";  
  63.             return "success";  
  64.         }  
  65. }  


这里没有显示全部的信息,提供了一个存储部分天气信息的类:

?
    public class WeatherBean {  
  1.     private String CityName;  
  2.     private String Temp;  
  3.     private String Weather;  
  4.     private String WeatherPicture;  
  5.     private String LiveWeather;  
  6.     private String CityDetail;  
  7.     public String getCityName() {  
  8.         return CityName;  
  9.     public void setCityName(String cityName) {  
  10.         CityName = cityName;  
  11.     public String getLiveWeather() {  
  12.         return LiveWeather;  
  13.     public void setLiveWeather(String liveWeather) {  
  14.         LiveWeather = liveWeather;  
  15.     public String getTemp() {  
  16.         return Temp;  
  17.     public void setTemp(String temp) {  
  18.         Temp = temp;  
  19.     public String getWeather() {  
  20.         return Weather;  
  21.     public void setWeather(String weather) {  
  22.         Weather = weather;  
  23.     public String getWeatherPicture() {  
  24.         return WeatherPicture;  
  25.     public void setWeatherPicture(String weatherPicture) {  
  26.         WeatherPicture = weatherPicture;  
  27.     public String getCityDetail() {  
  28.         return CityDetail;  
  29.     public void setCityDetail(String cityDetail) {  
  30.         CityDetail = cityDetail;  
  31. }  

 

显示天气状况的weather.xml文件

?
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
  1.     <LinearLayout  
  2.         android:layout_width="fill_parent"  
  3.         android:layout_height="wrap_content"  
  4.         android:orientation="vertical" >  
  5.         <TableLayout  
  6.             android:layout_width="fill_parent"  
  7.             android:layout_height="wrap_content" >  
  8.             <TableRow>  
  9.                 <TextView  
  10.                     android:layout_width="fill_parent"  
  11.                     android:layout_height="wrap_content"  
  12.                     android:text="天气实况:"  
  13.                     android:textSize="16sp" />  
  14.                 <ImageView  
  15.                     android:id="@+id/picture"  
  16.                     android:layout_width="wrap_content"  
  17.                     android:layout_height="wrap_content" />  
  18.             </TableRow>  
  19.                     android:layout_width="wrap_content"  
  20.                     android:layout_weight="1"  
  21.                     android:text="城市:"  
  22.                     android:textSize="16sp" />  
  23.                 <EditText  
  24.                     android:id="@+id/city_name"  
  25.                     android:layout_weight="2"  
  26.                     android:hint="城市名称"  
  27.                     android:editable="false" />  
  28.                     android:text="温度:"  
  29.                     android:id="@+id/temp"  
  30.                     android:hint="今日气温"  
  31.                     android:text="天气:"  
  32.                     android:id="@+id/weather"  
  33.                     android:hint="今日天气"  
  34.         </TableLayout>  
  35.         <TextView  
  36.             android:id="@+id/today_weather"  
  37.             android:layout_width="fill_parent"  
  38.             android:layout_height="wrap_content"  
  39.             android:textSize="16sp" />  
  40.             android:layout_height="wrap_content"  
  41.             android:text="城市简介:"  
  42.             android:id="@+id/city_detail"  
  43.     </LinearLayout>  
  44. </ScrollView>  


效果图如图:

这里许多功能做得不是很完善,大家可以根据自己的需要进行设计~


点击进入代码下载

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐