Android:WebService使用实例

来源:互联网 发布:mac python 当前路径 编辑:程序博客网 时间:2024/05/14 15:44

最近刚刚开始学习使用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文档中可以查看命名空间),以及调用方法名称。如:

//命名空间
privatestatic final String serviceNameSpace="http://WebXml.com.cn/";
//调用方法(获得支持的城市)
privatestatic 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
privatestatic final String serviceURL="http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
//Android传输对象
AndroidHttpTransport transport=new AndroidHttpTransport(serviceURL);
transport.debug=
true;

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

transport.call(serviceNameSpace+getWeatherbyCityName, envelope);

第七步:解析返回数据:

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

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

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

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

public class MainActivity extends Activity {// WSDL文档中的命名空间private static final String targetNameSpace = "http://WebXml.com.cn/";// WSDL文档中的URLprivate static final String WSDL = "http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";// 需要调用的方法名(获得本天气预报Web Services支持的洲、国内外省份和城市信息)private static final String getSupportProvince = "getSupportProvince";private List<Map<String,String>> listItems;private ListView mListView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listItems = new ArrayList<Map<String,String>>();mListView = (ListView) findViewById(R.id.province_list);new NetAsyncTask().execute();mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {String mProvinceName = listItems.get(position).get("province");Log.d("ProvinceName", mProvinceName);Intent intent = new Intent();intent.putExtra("Pname", mProvinceName);intent.setClass(MainActivity.this, CityActivity.class);startActivity(intent);}});}class NetAsyncTask extends AsyncTask<Object, Object, String> {@Overrideprotected void onPostExecute(String result) {if (result.equals("success")) {//列表适配器SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this, listItems, R.layout.province_item, new String[] {"province"}, new int[]{R.id.province});mListView.setAdapter(simpleAdapter);}super.onPostExecute(result);}@Overrideprotected String doInBackground(Object... params) {// 根据命名空间和方法得到SoapObject对象SoapObject soapObject = new SoapObject(targetNameSpace,getSupportProvince);// 通过SOAP1.1协议得到envelop对象SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);// 将soapObject对象设置为envelop对象,传出消息envelop.dotNet = true;envelop.setOutputSoapObject(soapObject);// 或者envelop.bodyOut = soapObject;HttpTransportSE httpSE = new HttpTransportSE(WSDL);// 开始调用远程方法try {httpSE.call(targetNameSpace + getSupportProvince, envelop);// 得到远程方法返回的SOAP对象SoapObject resultObj = (SoapObject) envelop.getResponse();// 得到服务器传回的数据int count = resultObj.getPropertyCount();for (int i = 0; i < count; i++) {Map<String,String> listItem = new HashMap<String, String>();listItem.put("province", resultObj.getProperty(i).toString());listItems.add(listItem);}} catch (IOException e) {e.printStackTrace();return "IOException";} catch (XmlPullParserException e) {e.printStackTrace();return "XmlPullParserException";}return "success";}}}

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

<LinearLayout xmlns: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文件:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns: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支持的国内外城市或地区信息:

public class CityActivity extends Activity {// WSDL文档中的命名空间private static final String targetNameSpace = "http://WebXml.com.cn/";// WSDL文档中的URLprivate static final String WSDL = "http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";// 需要调用的方法名(获得本天气预报Web Services支持的城市信息,根据省份查询城市集合:带参数)private static final String getSupportCity = "getSupportCity";private List<Map<String,String>> listItems;private ListView mListView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listItems = new ArrayList<Map<String,String>>();mListView = (ListView) findViewById(R.id.province_list);new NetAsyncTask().execute();//列表单击事件监听mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {String mCityName = listItems.get(position).get("city");String cityName = getCityName(mCityName);Log.d("CityName", cityName);Intent intent = new Intent();//存储选择的城市名intent.putExtra("Cname", cityName);intent.setClass(CityActivity.this, WeatherActivity.class);startActivity(intent);}});}/** * 拆分“城市 (代码)”字符串,将“城市”字符串分离 * @param name * @return */public String getCityName(String name) {String city = "";int position = name.indexOf(' ');city = name.substring(0, position);return city;}class NetAsyncTask extends AsyncTask<Object, Object, String> {@Overrideprotected void onPostExecute(String result) {if (result.equals("success")) {//列表适配器SimpleAdapter simpleAdapter = new SimpleAdapter(CityActivity.this, listItems, R.layout.province_item, new String[] {"city"}, new int[]{R.id.province});mListView.setAdapter(simpleAdapter);}super.onPostExecute(result);}@Overrideprotected String doInBackground(Object... params) {// 根据命名空间和方法得到SoapObject对象SoapObject soapObject = new SoapObject(targetNameSpace,getSupportCity);//参数输入String name = getIntent().getExtras().getString("Pname");soapObject.addProperty("byProvinceName", name);// 通过SOAP1.1协议得到envelop对象SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);// 将soapObject对象设置为envelop对象,传出消息envelop.dotNet = true;envelop.setOutputSoapObject(soapObject);HttpTransportSE httpSE = new HttpTransportSE(WSDL);// 开始调用远程方法try {httpSE.call(targetNameSpace + getSupportCity, envelop);// 得到远程方法返回的SOAP对象SoapObject resultObj = (SoapObject) envelop.getResponse();// 得到服务器传回的数据int count = resultObj.getPropertyCount();for (int i = 0; i < count; i++) {Map<String,String> listItem = new HashMap<String, String>();listItem.put("city", resultObj.getProperty(i).toString());listItems.add(listItem);}} catch (IOException e) {e.printStackTrace();return "IOException";} catch (XmlPullParserException e) {e.printStackTrace();return "XmlPullParserException";}return "success";}}}


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


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

public class WeatherActivity extends Activity {//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";    //根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数    private static final String getWeatherbyCityName="getWeatherbyCityName";    WeatherBean mWBean;    private ImageView mImageView;    private EditText mCityName;    private EditText mTemp;    private EditText mWeather;    private TextView mToday;    private TextView mDetail;    private int Image[];    @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.weather);Image = new int[]{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 = new WeatherBean();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);new NetAsyncTask().execute();}class NetAsyncTask extends AsyncTask<Object, Object, String> {@Overrideprotected void onPostExecute(String result) {String image = mWBean.getWeatherPicture();int position = 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);}public int getImageId(String picture) {int id = 0;int tempId = picture.indexOf('.');String sub = picture.substring(0, tempId);id = Integer.parseInt(sub);return id;}@Overrideprotected String doInBackground(Object... params) {// 根据命名空间和方法得到SoapObject对象SoapObject soapObject = new SoapObject(targetNameSpace,getWeatherbyCityName);String city = getIntent().getExtras().getString("Cname");soapObject.addProperty("theCityName",city);//调用的方法参数与参数值(根据具体需要可选可不选)// 通过SOAP1.1协议得到envelop对象SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);// 将soapObject对象设置为envelop对象,传出消息envelop.dotNet = true;envelop.setOutputSoapObject(soapObject);// 或者envelop.bodyOut = soapObject;HttpTransportSE httpSE = new HttpTransportSE(WSDL);// 开始调用远程方法try {httpSE.call(targetNameSpace + getWeatherbyCityName, envelop);// 得到远程方法返回的SOAP对象SoapObject resultObj = (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 (IOException e) {e.printStackTrace();return "IOException";} catch (XmlPullParserException e) {e.printStackTrace();return "XmlPullParserException";}return "success";}}}


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

public class WeatherBean {private String CityName;private String Temp;private String Weather;private String WeatherPicture;private String LiveWeather;private String CityDetail;public String getCityName() {return CityName;}public void setCityName(String cityName) {CityName = cityName;}public String getLiveWeather() {return LiveWeather;}public void setLiveWeather(String liveWeather) {LiveWeather = liveWeather;}public String getTemp() {return Temp;}public void setTemp(String temp) {Temp = temp;}public String getWeather() {return Weather;}public void setWeather(String weather) {Weather = weather;}public String getWeatherPicture() {return WeatherPicture;}public void setWeatherPicture(String weatherPicture) {WeatherPicture = weatherPicture;}public String getCityDetail() {return CityDetail;}public void setCityDetail(String cityDetail) {CityDetail = cityDetail;}}

 

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

<?xml version="1.0" encoding="utf-8"?><ScrollView xmlns: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>


效果图如图:

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


点击进入代码下载