WebService使用实例
近期刚刚開始学习使用WebService的方法进行server端数据交互,发现网上的资料不是非常全,
眼下就结合收集到的一些资料做了一个小样例和大家分享一下~
我们在PC机器javaclient中。须要一些库,比方XFire,Axis2,CXF等等来支持訪问WebService,可是这些库并不适合我们资源有限的android手机client,做过JAVA
ME的人都知道有KSOAP这个第三方的类库。能够帮助我们获取server端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,即能够再project的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:命名空间+方法名称,2:Envelope对象):
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文档中的URL
- private 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;
- @Override
- protected 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() {
- @Override
-
public 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> {
- @Override
- protected 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);
- }
- @Override
- protected 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();
- // 得到server传回的数据
- 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文档中的URL
- private 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;
- @Override
- protected 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() {
- @Override
- public 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> {
- @Override
- protected 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);
- }
- @Override
- protected 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();
- // 得到server传回的数据
- 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[];
- @Override
- protected 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> {
- @Override
- protected 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;
- }
- @Override
- protected 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();
- // 得到server传回的数据
- 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>
效果图如图:
这里很多功能做得不是非常完好,大家能够依据自己的须要进行设计~