Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 借助工具類輕鬆實現基於 WebService 的網絡編程

編輯:Android 開發實例

在日常開發中,我們接觸最多的網絡協議莫過於 HTTP。通過 GET 或 POST 方法調用數據接口,服務器返回 JSON 格式的數據,我們再解析並呈現給用戶——這條路徑相信大家都非常熟悉。相比其他格式,JSON 因為解析方便而備受青睞,社區裡也有 GSON、FastJson 等成熟的解析庫。就個人也更推薦阿里巴巴的 FastJson,我在實際項目中就一直用它來解析。不過,並非所有服務端都提供 JSON 接口,有些時候我們需要調用基於 SOAP 協議的 WebService 接口。

WebService 是一種基於 SOAP 協議的遠程調用標準,它能夠把不同操作系統、不同編程語言、不同技術平台整合到一起。遺憾的是,Android SDK 並沒有內置調用 WebService 的庫,因此我們需要引入第三方 SDK。PC 端的 WebService 客戶端庫可謂琳琅滿目,比如 Axis2、CXF,但它們對於移動端來說過於龐大,移植到 Android 上也並不輕鬆,所以並不在我們的考慮範圍之內。真正適合手機端的 WebService 客戶端 SDK 中,Ksoap2 是相當常用的一個。你可以從它的開源主頁下載對應的 jar 包,放進 libs 目錄即可使用。接下來,就帶大家動手調用 WebService 接口。

一、準備工作

首先新建一個名為 WebServiceDemo 的工程。我們選擇一個免費的公開 WebService 接口來做演示——這裡使用天氣接口 https://www.webxml.com.cn/WebServices/WeatherWebService.asmx,它能提供豐富的天氣數據,非常適合練手。

二、編寫 WebService 工具類

接下來我們封裝一個 WebService 工具類,把調用邏輯統一收攏。以後再遇到調用 WebService 的需求,直接拷貝過來改改就能用,非常省事。

package com.example.webservicedemo;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.os.Handler;
import android.os.Message;

/**
 * 訪問 WebService 的工具類
 */
public class WebServiceUtils {

    public static final String WEB_SERVER_URL = "https://www.webxml.com.cn/WebServices/WeatherWebService.asmx";

    // 含有 3 個線程的線程池
    private static final ExecutorService executorService = Executors.newFixedThreadPool(3);

    // 命名空間
    private static final String NAMESPACE = "https://WebXml.com.cn/";

    /**
     * @param url                 WebService 服務器地址
     * @param methodName          WebService 的調用方法名
     * @param properties          WebService 的參數
     * @param webServiceCallBack  回調接口
     */
    public static void callWebService(String url, final String methodName,
                                      HashMap<String, String> properties,
                                      final WebServiceCallBack webServiceCallBack) {

        // 創建 HttpTransportSE 對象,傳遞 WebService 服務器地址
        final HttpTransportSE httpTransportSE = new HttpTransportSE(url);
        // 創建 SoapObject 對象
        SoapObject soapObject = new SoapObject(NAMESPACE, methodName);

        // 為 SoapObject 添加參數
        if (properties != null) {
            for (Iterator<Map.Entry<String, String>> it = properties.entrySet().iterator(); it.hasNext();) {
                Map.Entry<String, String> entry = it.next();
                soapObject.addProperty(entry.getKey(), entry.getValue());
            }
        }

        // 實例化 SoapSerializationEnvelope,傳入 SOAP 協議版本號
        final SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        soapEnvelope.setOutputSoapObject(soapObject);
        soapEnvelope.dotNet = true; // 設置是否為 .Net 開發的 WebService
        httpTransportSE.debug = true;

        // 用於子線程與主線程通信的 Handler
        final Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                // 將返回值回調到 callBack 參數中
                webServiceCallBack.callBack((SoapObject) msg.obj);
            }
        };

        // 開啟線程去訪問 WebService
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                SoapObject resultSoapObject = null;
                try {
                    httpTransportSE.call(NAMESPACE + methodName, soapEnvelope);
                    if (soapEnvelope.getResponse() != null) {
                        resultSoapObject = (SoapObject) soapEnvelope.bodyIn;
                    }
                } catch (HttpResponseException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } finally {
                    // 將獲取的消息利用 Handler 發送到主線程
                    mHandler.sendMessage(mHandler.obtainMessage(0, resultSoapObject));
                }
            }
        });
    }

    public interface WebServiceCallBack {
        public void callBack(SoapObject result);
    }
}

我們只需調用其中的 callWebService(String url, String methodName, HashMap<String, String> properties, WebServiceCallBack webServiceCallBack) 方法,就能拿到想要的數據。它的實現思路可以總結為以下幾步:

1. 創建 HttpTransportSE 對象,通過構造方法指定 WebService 的 WSDL 文檔地址;
2. 創建 SoapObject 對象,傳入 WebService 的命名空間和調用方法名;
3. 設置調用方法的參數——若無參數則略過,有參數則通過 addProperty(String name, Object value) 逐個加入 SoapObject;
4. 實例化 SoapSerializationEnvelope,傳入 SOAP 協議版本號,用 setOutputSoapObject() 把 SoapObject 設進去,並配置是否為 .Net WebService、是否 debug 等信息;
5. 由於涉及網絡操作,我們用線程池異步調用 WebService。在子線程中調用 HttpTransportSE 的 call(String soapAction, SoapEnvelope envelope) 完成請求,再通過 soapEnvelope.bodyIn 取得返回結果;最後借助 Handler 完成子線程到主線程的切換,在 handleMessage() 里把結果回調給外部。

三、實際應用:省—市—天氣三級菜單

整體思路很簡單:先用一個 ListView 展示所有省份,點擊某個省進入城市列表(同樣用 ListView 呈現),最後點擊城市,用 TextView 展示查詢到的天氣詳情。

展示省份的布局裡只有一個 ListView:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/province_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="@android:color/transparent"
        android:fadingEdge="none">
    </ListView>

</RelativeLayout>

MainActivity 先通過工具類調用 WebService,再在回調方法 callBack(SoapObject result) 中把數據解析進一個 List<String>,最後給 ListView 設置適配器:

package com.example.webservicedemo;

import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.webservicedemo.WebServiceUtils.WebServiceCallBack;

/**
 * 顯示天氣省份的 Activity
 */
public class MainActivity extends Activity {

    private List<String> provinceList = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        final ListView mProvinceList = (ListView) findViewById(R.id.province_list);

        // 顯示進度條
        ProgressDialogUtils.showProgressDialog(this, "數據加載中...");

        // 通過工具類調用 WebService 接口
        WebServiceUtils.callWebService(WebServiceUtils.WEB_SERVER_URL, "getSupportProvince", null, new WebServiceCallBack() {

            // WebService 返回的數據回調到此方法
            @Override
            public void callBack(SoapObject result) {
                ProgressDialogUtils.dismissProgressDialog();
                if (result != null) {
                    provinceList = parseSoapObject(result);
                    mProvinceList.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, provinceList));
                } else {
                    Toast.makeText(MainActivity.this, "獲取 WebService 數據錯誤", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mProvinceList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent(MainActivity.this, CityActivity.class);
                intent.putExtra("province", provinceList.get(position));
                startActivity(intent);
            }
        });
    }

    /**
     * 解析 SoapObject 對象
     */
    private List<String> parseSoapObject(SoapObject result) {
        List<String> list = new ArrayList<String>();
        SoapObject provinceSoapObject = (SoapObject) result.getProperty("getSupportProvinceResult");
        if (provinceSoapObject == null) {
            return null;
        }
        for (int i = 0; i < provinceSoapObject.getPropertyCount(); i++) {
            list.add(provinceSoapObject.getProperty(i).toString());
        }
        return list;
    }
}

點擊省份後進入對應的城市列表。城市頁面同樣用 ListView 展示,布局與上面一致,Activity 代碼也大同小異,這裡直接看代碼:

package com.example.webservicedemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.ksoap2.serialization.SoapObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.webservicedemo.WebServiceUtils.WebServiceCallBack;

/**
 * 顯示城市的 Activity
 */
public class CityActivity extends Activity {

    private List<String> cityStringList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        final ListView mCityList = (ListView) findViewById(R.id.province_list);

        // 顯示進度條
        ProgressDialogUtils.showProgressDialog(this, "數據加載中...");

        // 添加參數
        HashMap<String, String> properties = new HashMap<String, String>();
        properties.put("byProvinceName", getIntent().getStringExtra("province"));

        WebServiceUtils.callWebService(WebServiceUtils.WEB_SERVER_URL, "getSupportCity", properties, new WebServiceCallBack() {

            @Override
            public void callBack(SoapObject result) {
                ProgressDialogUtils.dismissProgressDialog();
                if (result != null) {
                    cityStringList = parseSoapObject(result);
                    mCityList.setAdapter(new ArrayAdapter<String>(CityActivity.this, android.R.layout.simple_list_item_1, cityStringList));
                } else {
                    Toast.makeText(CityActivity.this, "獲取 WebService 數據錯誤", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mCityList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent(CityActivity.this, WeatherActivity.class);
                intent.putExtra("city", cityStringList.get(position));
                startActivity(intent);
            }
        });
    }

    /**
     * 解析 SoapObject 對象
     */
    private List<String> parseSoapObject(SoapObject result) {
        List<String> list = new ArrayList<String>();
        SoapObject provinceSoapObject = (SoapObject) result.getProperty("getSupportCityResult");
        for (int i = 0; i < provinceSoapObject.getPropertyCount(); i++) {
            String cityString = provinceSoapObject.getProperty(i).toString();
            list.add(cityString.substring(0, cityString.indexOf("(")).trim());
        }
        return list;
    }
}

最後,點擊對應城市調用 WebService 接口,獲取該城市的天氣詳情。為了簡單起見,我用一個 TextView 來展示天氣信息。由於天氣內容較多、一屏顯示不下,所以在外層套了一個 ScrollView 支持滾動:

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/weather"
                android:textColor="#336598"
                android:textSize="16sp"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

WeatherActivity 的代碼與前面大同小異,就不再贅述:

package com.example.webservicedemo;

import java.util.HashMap;

import org.ksoap2.serialization.SoapObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.example.webservicedemo.WebServiceUtils.WebServiceCallBack;

/**
 * 顯示天氣的 Activity
 */
public class WeatherActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weather_layout);
        init();
    }

    private void init() {
        final TextView mTextWeather = (TextView) findViewById(R.id.weather);
        ProgressDialogUtils.showProgressDialog(this, "數據加載中...");

        HashMap<String, String> properties = new HashMap<String, String>();
        properties.put("theCityName", getIntent().getStringExtra("city"));

        WebServiceUtils.callWebService(WebServiceUtils.WEB_SERVER_URL, "getWeatherbyCityName", properties, new WebServiceCallBack() {

            @Override
            public void callBack(SoapObject result) {
                ProgressDialogUtils.dismissProgressDialog();
                if (result != null) {
                    SoapObject detail = (SoapObject) result.getProperty("getWeatherbyCityNameResult");
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < detail.getPropertyCount(); i++) {
                        sb.append(detail.getProperty(i)).append("\r\n");
                    }
                    mTextWeather.setText(sb.toString());
                } else {
                    Toast.makeText(WeatherActivity.this, "獲取 WebService 數據錯誤", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

四、清單配置與權限聲明

編碼工作到此完成。運行前,別忘了在 AndroidManifest.xml 中註冊各個 Activity,並添加訪問網絡的權限:

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name="com.example.webservicedemo.MainActivity"
        android:label="@string/title_activity_main">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".CityActivity" />
    <activity android:name=".WeatherActivity"></activity>
</application>

<uses-permission android:name="android.permission.INTERNET" />

至此,一個完整的 WebService 網絡編程示例就誕生了。如果你希望省份、城市列表支持 A-Z 排序,也可以自行擴展實現,這裡就不再展開了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved