• 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服务器地址

    1. final HttpTransportSE httpSE = new HttpTransportSE(SERVER_URL);  

      2、 创建SoapObject对象,创建该对象时需要传入所要调用Wb Service的命名空间、Web Service方法名;如果有参数要传给Web Service服务器,调用SoapObject对象的addProperty(String name,Object value)方法来设置参数,该方法的name参数指定参数名;value参数指定参数值

    1. SoapObject soapObject = new SoapObject(PACE, M_NAME);  
    1. soapObject.addProperty("byProvinceName ", citys);  

    3、创建SoapSerializationEnelope对象,并传入SOAP协议的版本号;并设置对象的bodyOut属性

    1. final SoapSerializationEnvelope soapserial = new SoapSerializationEnvelope(  
    2.             SoapEnvelope.VER11);  
    3.     soapserial.bodyOut = soapObject;  
    4.     // 设置与.NET提供的Web service保持有良好的兼容性  
    5.     soapserial.dotNet = true;  

      6、调用HttpTransportSE对象的call()方法,其中call的第一个参数soapAction,第二个为SoapSerializationEvelope对象 调用远程Web Service;

    1. // 调用HttpTransportSE对象的call方法来调用 webserice  
    2.    httpSE.call(PACE + M_NAME, soapserial);  

       7、获取返回的信息,并解析

    1. // 获取服务器响应返回的SOAP消息  
    2. SoapObject result = (SoapObject) soapserial.bodyIn;  
    3. SoapObject detail = (SoapObject) result.getProperty("getSupportProvinceResult");  
    4. //解析返回信息  
    5. for (int i = 0; i < detail.getPropertyCount(); i++) {  
    6. citys.add(detail.getProperty(i).toString());  
    7. }  


    实例:通过天气预报 Web 服务 http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

    MainActivity.java

    1. package com.example.webserviceteset;  
    2.   
    3. import java.util.List;  
    4.   
    5. import android.app.Activity;  
    6. import android.os.Bundle;  
    7. import android.view.Menu;  
    8. import android.view.View;  
    9.   
    10. import android.widget.AdapterView;  
    11. import android.widget.ImageView;  
    12. import android.widget.TextView;  
    13. import android.widget.AdapterView.OnItemSelectedListener;  
    14. import android.widget.ArrayAdapter;  
    15.   
    16. import android.widget.Spinner;  
    17.   
    18. public class MainActivity extends Activity {  
    19.   
    20.     private Spinner city, citys;  
    21.     private List<String> listcity, listcitys, weater;  
    22.     // 分别显示近三天的天气信息和城市介绍  
    23.     private TextView cityNames1, cityNames2, cityNames3, cityjie;  
    24.     private ImageView weateImage1, weateImage2, weateImage3;  
    25.   
    26.     @Override  
    27.     protected void onCreate(Bundle savedInstanceState) {  
    28.         super.onCreate(savedInstanceState);  
    29.         setContentView(R.layout.activity_main);  
    30.         citys = (Spinner) findViewById(R.id.citys);  
    31.         city = (Spinner) findViewById(R.id.city);  
    32.         cityNames1 = (TextView) findViewById(R.id.cityNames1);  
    33.         cityNames2 = (TextView) findViewById(R.id.cityNames2);  
    34.         cityNames3 = (TextView) findViewById(R.id.cityNames3);  
    35.         cityjie = (TextView) findViewById(R.id.cityjie);  
    36.         weateImage1 = (ImageView) findViewById(R.id.weateImage1);  
    37.         weateImage2 = (ImageView) findViewById(R.id.weateImage2);  
    38.         weateImage3 = (ImageView) findViewById(R.id.weateImage3);  
    39.   
    40.         // cityNames1=(TextView)findViewById(R.i)  
    41.         listcitys = WebServiceTest.getCitys();  
    42.         ArrayAdapter<String> citysAdater = new ArrayAdapter<String>(this,  
    43.                 android.R.layout.simple_list_item_multiple_choice, listcitys);  
    44.         citys.setAdapter(citysAdater);  
    45.         listcity = WebServiceTest.getCity(citys.getSelectedItem().toString());  
    46.         ArrayAdapter<String> cityAdater = new ArrayAdapter<String>(this,  
    47.                 android.R.layout.simple_list_item_multiple_choice, listcity);  
    48.         city.setAdapter(cityAdater);  
    49.         citys.setOnItemSelectedListener(new OnItemSelectedListener() {  
    50.   
    51.             @Override  
    52.             public void onItemSelected(AdapterView<?> arg0, View arg1,  
    53.                     int arg2, long arg3) {  
    54.                 listcity = WebServiceTest.getCity(citys.getSelectedItem()  
    55.                         .toString());  
    56.                 ArrayAdapter<String> cityAdater1 = new ArrayAdapter<String>(  
    57.                         MainActivity.this,  
    58.                         android.R.layout.simple_list_item_multiple_choice,  
    59.                         listcity);  
    60.                 city.setAdapter(cityAdater1);  
    61.   
    62.             }  
    63.   
    64.             @Override  
    65.             public void onNothingSelected(AdapterView<?> arg0) {  
    66.                 // TODO Auto-generated method stub  
    67.   
    68.             }  
    69.         });  
    70.         city.setOnItemSelectedListener(new OnItemSelectedListener() {  
    71.             // 返回数据: 一个一维数组 String(22),共有23个元素。  
    72.             @Override  
    73.             public void onItemSelected(AdapterView<?> arg0, View arg1,  
    74.                     int arg2, long arg3) {  
    75.                 weater = WebServiceTest.getWeather(city.getSelectedItem()  
    76.                         .toString());  
    77.   
    78.                 for (int i = 0; i < weater.size(); i++) {  
    79.                     System.out.println("i=" + i + ":" + weater.get(i));  
    80.                 }  
    81.   
    82.                 cityNames1.setText(weater.get(6) + " " + weater.get(5) + " "  
    83.                         + weater.get(7));  
    84.                 cityNames1.setBackgroundResource(ChangeImageView.imageId(weater  
    85.                         .get(8)));  
    86.                 weateImage1.setImageResource(ChangeImageView.imageId(weater  
    87.                         .get(8)));  
    88.                 cityNames2.setText(weater.get(13) + " " + weater.get(12) + " "  
    89.                         + weater.get(14));  
    90.                 cityNames2.setBackgroundResource(ChangeImageView.imageId(weater  
    91.                         .get(15)));  
    92.                 weateImage2.setImageResource(ChangeImageView.imageId(weater  
    93.                         .get(15)));  
    94.                 cityNames3.setText(weater.get(18) + " " + weater.get(17) + " "  
    95.                         + weater.get(19));  
    96.                 cityNames3.setBackgroundResource(ChangeImageView.imageId(weater  
    97.                         .get(20)));  
    98.                 weateImage3.setImageResource(ChangeImageView.imageId(weater  
    99.                         .get(21)));  
    100.                 cityjie.setText(weater.get(22));  
    101.                   
    102.                   
    103.             }  
    104.   
    105.             @Override  
    106.             public void onNothingSelected(AdapterView<?> arg0) {  
    107.                 // TODO Auto-generated method stub  
    108.   
    109.             }  
    110.         });  
    111.   
    112.     }  
    113.   
    114.     @Override  
    115.     public boolean onCreateOptionsMenu(Menu menu) {  
    116.         getMenuInflater().inflate(R.menu.main, menu);  
    117.         return true;  
    118.     }  
    119.   
    120. }  

    WebServiceTest.java

    1. package com.example.webserviceteset;  
    2.   
    3. import java.util.ArrayList;  
    4. import java.util.List;  
    5. import java.util.concurrent.Callable;  
    6. import java.util.concurrent.ExecutionException;  
    7. import java.util.concurrent.FutureTask;  
    8.   
    9. import org.ksoap2.SoapEnvelope;  
    10. import org.ksoap2.serialization.SoapObject;  
    11. import org.ksoap2.serialization.SoapSerializationEnvelope;  
    12. import org.ksoap2.transport.HttpTransportSE;  
    13.   
    14. public class WebServiceTest {  
    15.   
    16.     // Webservice服务器地址  
    17.     private static final String SERVER_URL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";  
    18.     // 调用的webservice命令空间  
    19.     private static final String PACE = "http://WebXml.com.cn/";  
    20.     // 获取所有省份的方法名  
    21.     private static final String M_NAME = "getSupportProvince";  
    22.     // 获取省份包含的城市的方法名  
    23.     private static final String MC_NAME = "getSupportCity";  
    24.     // 获取天气详情的方法名  
    25.     private static final String W_NAME = "getWeatherbyCityName";  
    26.   
    27.     /** 
    28.      *  
    29.      * @return 所有省份 
    30.      */  
    31.   
    32.     public static List<String> getCitys() {  
    33.         // 创建HttpTransportSE传说对象 传入webservice服务器地址  
    34.         final HttpTransportSE httpSE = new HttpTransportSE(SERVER_URL);  
    35.         httpSE.debug = true;  
    36.         // 创建soapObject对象并传入命名空间和方法名  
    37.         SoapObject soapObject = new SoapObject(PACE, M_NAME);  
    38.   
    39.         // 创建SoapSerializationEnvelope对象并传入SOAP协议的版本号  
    40.         final SoapSerializationEnvelope soapserial = new SoapSerializationEnvelope(  
    41.                 SoapEnvelope.VER11);  
    42.         soapserial.bodyOut = soapObject;  
    43.         // 设置与.NET提供的Web service保持有良好的兼容性  
    44.         soapserial.dotNet = true;  
    45.         // 使用Callable与Future来创建启动线程  
    46.         FutureTask<List<String>> future = new FutureTask<List<String>>(  
    47.                 new Callable<List<String>>() {  
    48.                     @Override  
    49.                     public List<String> call() throws Exception {  
    50.                         List<String> citys = new ArrayList<String>();  
    51.                         // 调用HttpTransportSE对象的call方法来调用 webserice  
    52.                         httpSE.call(PACE + M_NAME, soapserial);  
    53.                         if (soapserial.getResponse() != null) {  
    54.                             // 获取服务器响应返回的SOAP消息  
    55.                             SoapObject result = (SoapObject) soapserial.bodyIn;  
    56.                             SoapObject detail = (SoapObject) result  
    57.                                     .getProperty("getSupportProvinceResult");  
    58.                             // 解析返回信息  
    59.                             for (int i = 0; i < detail.getPropertyCount(); i++) {  
    60.                                 citys.add(detail.getProperty(i).toString());  
    61.                             }  
    62.                             return citys;  
    63.                         }  
    64.                         return null;  
    65.                     }  
    66.                 });  
    67.         new Thread(future).start();  
    68.         try {  
    69.             return future.get();  
    70.         } catch (InterruptedException e) {  
    71.             // TODO Auto-generated catch block  
    72.             e.printStackTrace();  
    73.         } catch (ExecutionException e) {  
    74.             // TODO Auto-generated catch block  
    75.             e.printStackTrace();  
    76.         }  
    77.         return null;  
    78.     }  
    79.   
    80.     /** 
    81.      *  
    82.      * @param citys 
    83.      *            省份 
    84.      * @return 该省下的所有城市 
    85.      */  
    86.     public static List<String> getCity(String citys) {  
    87.   
    88.         // 创建HttpTransportSE对象  
    89.         final HttpTransportSE httpSE = new HttpTransportSE(SERVER_URL);  
    90.         httpSE.debug = true;  
    91.         // 创建SoapObject对象  
    92.         SoapObject soapObject = new SoapObject(PACE, MC_NAME);  
    93.         // 添加参数  
    94.         soapObject.addProperty("byProvinceName ", citys);  
    95.         // 创建SoapSerializationEnvelope  
    96.         final SoapSerializationEnvelope serializa = new SoapSerializationEnvelope(  
    97.                 SoapEnvelope.VER11);  
    98.         serializa.bodyOut = soapObject;  
    99.         serializa.dotNet = true;  
    100.         FutureTask<List<String>> future = new FutureTask<List<String>>(  
    101.                 new Callable<List<String>>() {  
    102.   
    103.                     @Override  
    104.                     public List<String> call() throws Exception {  
    105.                         List<String> city = new ArrayList<String>();  
    106.                         // 调用Web Service  
    107.                         httpSE.call(PACE + MC_NAME, serializa);  
    108.                         // 获取返回信息  
    109.                         if (serializa.getResponse() != null) {  
    110.                             SoapObject restul = (SoapObject) serializa.bodyIn;  
    111.                             SoapObject detial = (SoapObject) restul  
    112.                                     .getProperty("getSupportCityResult");  
    113.                             // 解析返回信息  
    114.                             for (int i = 0; i < detial.getPropertyCount(); i++) {  
    115.                                 // 获取城市名  
    116.                                 String str = detial.getPropertyAsString(i)  
    117.                                         .toString();  
    118.                                 String strCity = str.substring(0,  
    119.                                         str.indexOf("(") - 1);  
    120.                                 city.add(strCity);  
    121.                             }  
    122.                             return city;  
    123.                         }  
    124.                         return null;  
    125.                     }  
    126.                 });  
    127.         new Thread(future).start();  
    128.         try {  
    129.             return future.get();  
    130.         } catch (InterruptedException e) {  
    131.             // TODO Auto-generated catch block  
    132.             e.printStackTrace();  
    133.         } catch (ExecutionException e) {  
    134.             // TODO Auto-generated catch block  
    135.             e.printStackTrace();  
    136.         }  
    137.         return null;  
    138.     }  
    139.   
    140.     // 获取三天之内的天气详情  
    141.     public static List<String> getWeather(String citys) {  
    142.         final HttpTransportSE httpSe = new HttpTransportSE(SERVER_URL);  
    143.         httpSe.debug = true;  
    144.         SoapObject soapObject = new SoapObject(PACE, W_NAME);  
    145.         soapObject.addProperty("theCityName", citys);  
    146.         final SoapSerializationEnvelope serializa = new SoapSerializationEnvelope(  
    147.                 SoapEnvelope.VER11);  
    148.         serializa.bodyOut = soapObject;  
    149.         serializa.dotNet = true;  
    150.         FutureTask<List<String>> future = new FutureTask<List<String>>(  
    151.                 new Callable<List<String>>() {  
    152.                     @Override  
    153.                     public List<String> call() throws Exception {  
    154.                         List<String> list = new ArrayList<String>();  
    155.                         // 调用webservice  
    156.                         httpSe.call(PACE+W_NAME, serializa);  
    157.                         // 获取返回信息  
    158.                         if (serializa.getResponse() != null) {  
    159.                             SoapObject result = (SoapObject) serializa.bodyIn;  
    160.                             SoapObject deialt = (SoapObject) result  
    161.                                     .getProperty("getWeatherbyCityNameResult");  
    162.                             // 解析数据  
    163.                             for (int i = 0; i < deialt.getPropertyCount(); i++) {  
    164.                                 list.add(deialt.getProperty(i).toString());  
    165.                             }  
    166.                         }  
    167.                         return list;  
    168.                     }  
    169.                 });  
    170.         new Thread(future).start();  
    171.         try {  
    172.             return future.get();  
    173.         } catch (InterruptedException e) {  
    174.             // TODO Auto-generated catch block  
    175.             e.printStackTrace();  
    176.         } catch (ExecutionException e) {  
    177.             // TODO Auto-generated catch block  
    178.             e.printStackTrace();  
    179.         }  
    180.         return null;  
    181.     }  
    182.   
    183. }  

    ChangeImageView.java

    1. package com.example.webserviceteset;  
    2.   
    3. public class ChangeImageView {  
    4.     // 由于下载下来的图片分 大中小 三种 而调用远程webserivce获取的值是小的图片名 所以的 根据获取的图片名称来获取向对应的大图片ID  
    5.     public static int imageId(String ids) {  
    6.           
    7.         int id = R.drawable.a_0;  
    8.         int ided =Integer.parseInt(ids.substring(0, ids.indexOf(".")));  
    9.         switch (ided) {  
    10.         case 1:  
    11.             id = R.drawable.a_1;  
    12.             break;  
    13.         case 2:  
    14.             id = R.drawable.a_2;  
    15.             break;  
    16.         case 3:  
    17.             id = R.drawable.a_3;  
    18.             break;  
    19.         case 4:  
    20.             id = R.drawable.a_4;  
    21.             break;  
    22.         case 5:  
    23.             id = R.drawable.a_5;  
    24.             break;  
    25.         case 6:  
    26.             id = R.drawable.a_6;  
    27.             break;  
    28.         case 7:  
    29.             id = R.drawable.a_7;  
    30.             break;  
    31.         case 8:  
    32.             id = R.drawable.a_8;  
    33.             break;  
    34.         case 9:  
    35.             id = R.drawable.a_9;  
    36.             break;  
    37.         case 10:  
    38.             id = R.drawable.a_10;  
    39.             break;  
    40.         case 11:  
    41.             id = R.drawable.a_11;  
    42.             break;  
    43.         case 12:  
    44.             id = R.drawable.a_12;  
    45.             break;  
    46.         case 13:  
    47.             id = R.drawable.a_13;  
    48.             break;  
    49.         case 14:  
    50.             id = R.drawable.a_1;  
    51.             break;  
    52.         case 15:  
    53.             id = R.drawable.a_15;  
    54.             break;  
    55.         case 16:  
    56.             id = R.drawable.a_16;  
    57.             break;  
    58.         case 17:  
    59.             id = R.drawable.a_17;  
    60.             break;  
    61.         case 18:  
    62.             id = R.drawable.a_18;  
    63.             break;  
    64.         case 19:  
    65.             id = R.drawable.a_19;  
    66.             break;  
    67.         case 20:  
    68.             id = R.drawable.a_20;  
    69.             break;  
    70.         case 21:  
    71.             id = R.drawable.a_21;  
    72.             break;  
    73.         case 22:  
    74.             id = R.drawable.a_22;  
    75.             break;  
    76.         case 23:  
    77.             id = R.drawable.a_23;  
    78.             break;  
    79.         case 24:  
    80.             id = R.drawable.a_24;  
    81.             break;  
    82.         case 25:  
    83.             id = R.drawable.a_25;  
    84.             break;  
    85.         case 26:  
    86.             id = R.drawable.a_26;  
    87.             break;  
    88.         case 27:  
    89.             id = R.drawable.a_27;  
    90.             break;  
    91.         case 28:  
    92.             id = R.drawable.a_28;  
    93.             break;  
    94.         case 29:  
    95.             id = R.drawable.a_29;  
    96.             break;  
    97.         case 30:  
    98.             id = R.drawable.a_30;  
    99.             break;  
    100.         }  
    101.         return id;  
    102.     }  
    103. }  

    activity_main.xml

    1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    2.     xmlns:tools="http://schemas.android.com/tools"  
    3.     android:layout_width="match_parent"  
    4.     android:layout_height="match_parent"  
    5.     android:orientation="vertical"  
    6.     tools:context=".MainActivity" >  
    7.   
    8.     <LinearLayout  
    9.         android:layout_width="wrap_content"  
    10.         android:layout_height="wrap_content"  
    11.         android:orientation="horizontal" >  
    12.   
    13.         <Spinner  
    14.             android:id="@+id/citys"  
    15.             android:layout_width="match_parent"  
    16.             android:layout_height="wrap_content" />  
    17.         <Spinner  
    18.             android:id="@+id/city"  
    19.             android:layout_width="match_parent"  
    20.             android:layout_height="wrap_content" />  
    21.     </LinearLayout>  
    22.   
    23.     <LinearLayout  
    24.         android:layout_width="wrap_content"  
    25.         android:layout_height="wrap_content"  
    26.         android:orientation="horizontal" >  
    27.   
    28.         <TextView  
    29.             android:id="@+id/cityNames1"  
    30.             android:layout_width="wrap_content"  
    31.             android:layout_height="wrap_content" />  
    32.   
    33.         <ImageView  
    34.             android:id="@+id/weateImage1"  
    35.             android:layout_width="wrap_content"  
    36.             android:layout_height="wrap_content" />  
    37.     </LinearLayout>  
    38.   
    39.     <LinearLayout  
    40.         android:layout_width="wrap_content"  
    41.         android:layout_height="wrap_content"  
    42.         android:orientation="horizontal" >  
    43.   
    44.         <TextView  
    45.             android:id="@+id/cityNames2"  
    46.             android:layout_width="wrap_content"  
    47.             android:layout_height="wrap_content" />  
    48.   
    49.         <ImageView  
    50.             android:id="@+id/weateImage2"  
    51.             android:layout_width="wrap_content"  
    52.             android:layout_height="wrap_content" />  
    53.     </LinearLayout>  
    54.   
    55.     <LinearLayout  
    56.         android:layout_width="wrap_content"  
    57.         android:layout_height="wrap_content"  
    58.         android:orientation="horizontal" >  
    59.   
    60.         <TextView  
    61.             android:id="@+id/cityNames3"  
    62.             android:layout_width="wrap_content"  
    63.             android:layout_height="wrap_content" />  
    64.   
    65.         <ImageView  
    66.             android:id="@+id/weateImage3"  
    67.             android:layout_width="wrap_content"  
    68.             android:layout_height="wrap_content" />  
    69.     </LinearLayout>  
    70.   
    71.     <LinearLayout  
    72.         android:layout_width="wrap_content"  
    73.         android:layout_height="wrap_content"  
    74.         android:orientation="horizontal" >  
    75.   
    76.         <TextView  
    77.             android:id="@+id/cityjie"  
    78.             android:layout_width="match_parent"  
    79.             android:layout_height="wrap_content"  
    80.             android:lines="6" />  
    81.     </LinearLayout>  
    82.   
    83. </LinearLayout>  
    84. AndroidManifest.xmlAndroidManifest.xml  

    AndroidManifest.xml

    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     package="com.example.webserviceteset"  
    4.     android:versionCode="1"  
    5.     android:versionName="1.0" >  
    6.   
    7.     <uses-sdk  
    8.         android:minSdkVersion="11"  
    9.         android:targetSdkVersion="17" />  
    10.     <uses-permission   
    11.         android:name="android.permission.INTERNET"/>  
    12.   
    13.     <application  
    14.         android:allowBackup="true"  
    15.         android:icon="@drawable/ic_launcher"  
    16.         android:label="@string/app_name"  
    17.         android:theme="@style/AppTheme" >  
    18.         <activity  
    19.             android:name="com.example.webserviceteset.MainActivity"  
    20.             android:label="@string/app_name" >  
    21.             <intent-filter>  
    22.                 <action android:name="android.intent.action.MAIN" />  
    23.   
    24.                 <category android:name="android.intent.category.LAUNCHER" />  
    25.             </intent-filter>  
    26.         </activity>  
    27.     </application>  
    28.   
    29. </manifest>  

    源代码下载的地址:http://files.cnblogs.com/android100/WebServiceTeset.rar

  • 相关阅读:
    Uva 11401 数三角形
    Uva 11538 象棋中的皇后
    数学基础——基本计数方法
    八数码问题
    python 爬poj.org的题目
    python 爬图片
    hiho 第135周 九宫
    Uva 11464 偶数矩阵
    BZOJ 1001 [BeiJing2006]狼抓兔子
    LA 3708 墓地雕塑
  • 原文地址:https://www.cnblogs.com/android100/p/Android-ksoap2-android.html
Copyright © 2020-2023  润新知