大家好,又见面了,我是全栈君。
近期刚刚開始学习使用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”;
- }
- }
- }