安卓中的SOAP消息和WebService

1、SOAP消息
簡單對象訪問協議(Simple Object Access Protocol,SOAP)是一種標準化的通信規範,主要用於Web服務(Web Service)。
SOAP使用Internet應用層協議作爲其傳輸協議。SMTP及HTTP協議都可以用來傳輸SOAP消息,SOAP亦可以通過HTTPS傳輸。一條SOAP消息就是一個普通的XML文檔,包含下列元素:
(1)必須的Envelope元素,可把此XML文檔標識爲一條SOAP消息。
(2)可選的Header元素,包含頭部信息。
(3)必須的Body元素,包含所有的調用和響應消息。
(4)可選的Fault元素,提供有關在處理此消息時發生錯誤的信息。
SOAP消息的重要語法規則如下:
(1)SOAP消息必須使用XML來編碼。
(2)SOAP消息必須使用SOAP Envelope命名空間。
(3)SOAP消息必須使用SOAP Encoding命名空間。
(4)SOAP消息不能包含DTD引用。
(5)SOAP消息不能包含XML處理指令。

2、調用WebService
SOAP調用WebService的具體步驟如下:

步驟一:添加ksoap2包。可以從網址http://code.google.com/p/ksoap2-android/下載,然後將下載的ksoap2-android-assembly-2.4-jar-with-dependencies.jar包複製到Eclipse工程的lib目錄中,當然也可以放在其他的目錄裏。在Eclipse中引用這個jar包。

步驟二:指定WebService的命名空間和調用的方法名,如:
SoapObject request = new SoapObject(http://service, “getName”);
SoapObject類的第一個參數表示WebService的命名空間,可以從WSDL文檔中找到WebService的命名空間;第二個參數表示要調用的WebService方法名。

步驟三:設置調用方法的參數值,如果沒有參數,可以省略。設置方法的參數值的代碼如下:
request.addProperty(“param1”,”value”);
request.addProperty(“param2”,”value”);
要注意的是,addProperty方法的第一個參數雖然表示調用方法的參數名,但該參數值並不一定與服務端的WebService類中的方法參數名一致,只要設置參數的順序一致即可。

步驟四:生成調用WebService方法的SOAP請求信息。該信息由SoapSerializationEnvelope對象描述,代碼如下:
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=request;
envelope.dotNet=true;
創建SoapSerializationEnvelope對象時需要通過SoapSerializationEnvelope類的構造方法設置SOAP協議的版本號。該版本號需要根據服務端WebService的版本號設置。在創建SoapSerializationEnvelope對象後,不要忘了設置SoapSerializationEnvelope類的bodyOut屬性,該屬性的值就是在步驟2創建的SoapObject對象。

步驟五:創建HttpTransportSE對象。通過HttpTransportSE類的構造方法可以指定WebService的WSDL文檔的URL。
HttpTransportSE ht=new HttpTransportSE (“http://……asmx?wsdl”);

步驟六:使用call方法調用WebService方法,代碼如下:
ht.call(null,envelope);
call方法的第一個參數一般爲null,第2個參數就是在步驟四創建的SoapSerializationEnvelope對象。

步驟七:使用getResponse方法獲得WebService方法的返回結果,代碼如下:
SoapObject soapObject=(SoapObject)envelope.getResponse();

步驟八:解析返回的內容。

3、代碼示例

public class WebServiceProvider {
    static final String NAMESPACE = "http://WebXml.com.cn/";
    static String endPoint;
    static String methodName;
    static String soapAction;

    public static String getPhoneSource(String phoneNum) {
        methodName = "getMobileCodeInfo";
        endPoint = "http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
        soapAction = NAMESPACE + methodName;

        SoapObject rpc = new SoapObject(NAMESPACE, methodName);
        // 設置需調用WebService接口需要傳入的兩個參數mobileCode、userId,不可以隨便寫,必須和提供的參數名相同
        rpc.addProperty("mobileCode", phoneNum);
        rpc.addProperty("userID", "");
        // 生成調用WebService方法的SOAP請求信息,並指定SOAP的版本
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.bodyOut = rpc;
        // 設置是否調用的是dotNet開發的WebService
        envelope.dotNet = true;
        // 等價於envelope.bodyOut = rpc;
        HttpTransportSE transport = new HttpTransportSE(endPoint);

        // 調用WebService
        try {
            transport.call(soapAction, envelope);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 獲取返回的數據
        SoapObject object = (SoapObject) envelope.bodyIn;

        // 獲取返回的結果
        String result = object.getProperty("getMobileCodeInfoResult")
                .toString();
        return result;
    }

    public static String[] getProvinceList() {
        methodName = "getRegionProvince";
        endPoint = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";
        soapAction = NAMESPACE + methodName;

        String[] provinceStrings;
        SoapObject rpc = new SoapObject(NAMESPACE, methodName);     
        // 生成調用WebService方法的SOAP請求信息,並指定SOAP的版本
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.bodyOut = rpc;
        // 設置是否調用的是dotNet開發的WebService
        envelope.dotNet = true;
        HttpTransportSE transport = new HttpTransportSE(endPoint);

        // 調用WebService
        try {
            transport.call(soapAction, envelope);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 獲取返回的數據
        SoapObject object = (SoapObject) envelope.bodyIn;
        SoapObject provinceSoapObject = (SoapObject) object
                .getProperty("getRegionProvinceResult");

        provinceStrings = new String[provinceSoapObject.getPropertyCount()];
        for (int i = 0; i < provinceSoapObject.getPropertyCount(); i++) {
            String provinceString = provinceSoapObject.getProperty(i)
                    .toString().split(",")[0];
            provinceStrings[i] = provinceString;
        }
        return provinceStrings;
    }

    public static String[] getCityList(String provinceString) {
        methodName = "getSupportCityString ";
        endPoint = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";
        soapAction = NAMESPACE + methodName;

        String[] cityStrings;
        SoapObject rpc = new SoapObject(NAMESPACE, methodName);
        // 設置需調用WebService接口需要傳入的兩個參數mobileCode、userId,不可以隨便寫,必須和提供的參數名相同
        rpc.addProperty("theRegionCode", provinceString);
        rpc.addProperty("userID", "你的ID");
        // 生成調用WebService方法的SOAP請求信息,並指定SOAP的版本
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.bodyOut = rpc;
        // 設置是否調用的是dotNet開發的WebService
        envelope.dotNet = true;
        HttpTransportSE transport = new HttpTransportSE(endPoint);

        // 調用WebService
        try {
            transport.call(soapAction, envelope);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 獲取返回的數據
        SoapObject object = (SoapObject) envelope.bodyIn;
        SoapObject citySoapObject = (SoapObject) object
                .getProperty("getSupportCityStringResult");

        cityStrings = new String[citySoapObject.getPropertyCount()];
        for (int i = 0; i < citySoapObject.getPropertyCount(); i++) {
            String cityString = citySoapObject.getProperty(i).toString()
                    .split(",")[0];
            cityStrings[i] = cityString;
        }
        return cityStrings;
    }

    public static HashMap<String, String> getWeather(String cityString) {
        methodName = "getWeather";
        endPoint = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";
        soapAction = NAMESPACE + methodName;

        HashMap<String, String> weatherInfos;
        SoapObject rpc = new SoapObject(NAMESPACE, methodName);
        // 設置需調用WebService接口需要傳入的兩個參數mobileCode、userId,不可以隨便寫,必須和提供的參數名相同
        rpc.addProperty("theCityCode", cityString);
        rpc.addProperty("theUserID", "你的ID");
        // 生成調用WebService方法的SOAP請求信息,並指定SOAP的版本
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.bodyOut = rpc;
        // 設置是否調用的是dotNet開發的WebService
        envelope.dotNet = true;
        HttpTransportSE transport = new HttpTransportSE(endPoint);

        // 調用WebService
        try {
            transport.call(soapAction, envelope);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 獲取返回的數據
        SoapObject object = (SoapObject) envelope.bodyIn;
        SoapObject weatherSoapObject = (SoapObject) object
                .getProperty("getWeatherResult");

        String todayDate = weatherSoapObject.getPropertyAsString(3);// 日期
        String todayTemp = "氣溫:"+weatherSoapObject.getPropertyAsString(4).split(";")[0].split(":")[2];// 溫度
        String todayWind = weatherSoapObject.getPropertyAsString(4).split(";")[1];// 風力
        String todayHumidity=weatherSoapObject.getPropertyAsString(4).split(";")[2];// 溼度       
        String todayImage = weatherSoapObject.getPropertyAsString(10);//圖片

        String tomorrowDate=weatherSoapObject.getPropertyAsString(12).split(" ")[0];// 明日時間
        String tomorrowWeather=weatherSoapObject.getPropertyAsString(12).split(" ")[1];// 明日天氣
        String tomorrowImage = weatherSoapObject.getPropertyAsString(15);//明日圖片
        String tomorrowTemp = weatherSoapObject.getPropertyAsString(13);// 明日溫度

        String tomorrow2Date=weatherSoapObject.getPropertyAsString(17).split(" ")[0];// 後天時間
        String tomorrow2Weather=weatherSoapObject.getPropertyAsString(17).split(" ")[1];// 明日天氣
        String tomorrow2Image = weatherSoapObject.getPropertyAsString(20);//後天圖片
        String tomorrow2Temp = weatherSoapObject.getPropertyAsString(18);// 後天溫度

        String tomorrow3Date=weatherSoapObject.getPropertyAsString(22).split(" ")[0];// 大後天時間
        String tomorrow3Weather=weatherSoapObject.getPropertyAsString(22).split(" ")[1];// 明日天氣
        String tomorrow3Image = weatherSoapObject.getPropertyAsString(25);//大後天圖片
        String tomorrow3Temp = weatherSoapObject.getPropertyAsString(23);// 大後天溫度

        weatherInfos = new HashMap<String, String>();
        weatherInfos.put("todayDate", todayDate);
        weatherInfos.put("todayTemp", todayTemp);
        weatherInfos.put("todayWind", todayWind);
        weatherInfos.put("todayHumidity", todayHumidity);
        weatherInfos.put("todayImage", todayImage);

        weatherInfos.put("tomorrowDate", tomorrowDate);
        weatherInfos.put("tomorrowWeather", tomorrowWeather);
        weatherInfos.put("tomorrowImage", tomorrowImage);
        weatherInfos.put("tomorrowTemp", tomorrowTemp);

        weatherInfos.put("tomorrow2Date", tomorrow2Date);
        weatherInfos.put("tomorrow2Weather", tomorrow2Weather);
        weatherInfos.put("tomorrow2Image", tomorrow2Image);
        weatherInfos.put("tomorrow2Temp", tomorrow2Temp);

        weatherInfos.put("tomorrow3Date", tomorrow3Date);
        weatherInfos.put("tomorrow3Weather", tomorrow3Weather);
        weatherInfos.put("tomorrow3Image", tomorrow3Image);
        weatherInfos.put("tomorrow3Temp", tomorrow3Temp);

        return weatherInfos;            
    }

    public static ArrayList<HashMap<String, String>> getFlightTimeList(String startCity,String lastCity,String flightDate) 
    {
        methodName = "getDomesticAirlinesTime";
        endPoint = "http://webservice.webxml.com.cn/webservices/DomesticAirline.asmx";
        soapAction = NAMESPACE + methodName;

        ArrayList<HashMap<String, String>> flights=new ArrayList<HashMap<String, String>>();
        SoapObject rpc = new SoapObject(NAMESPACE, methodName);
        // 設置需調用WebService接口需要傳入的兩個參數mobileCode、userId,不可以隨便寫,必須和提供的參數名相同
        rpc.addProperty("startCity", startCity);
        rpc.addProperty("lastCity", lastCity);
        rpc.addProperty("theDate", flightDate);
        rpc.addProperty("userID", "你的ID");
        // 生成調用WebService方法的SOAP請求信息,並指定SOAP的版本
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.bodyOut = rpc;
        // 設置是否調用的是dotNet開發的WebService
        envelope.dotNet = true;
        HttpTransportSE transport = new HttpTransportSE(endPoint);

        // 調用WebService
        try {
            transport.call(soapAction, envelope);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 獲取返回的數據
        SoapObject object = (SoapObject) envelope.bodyIn;
        SoapObject airLinesTimeSoapObject = (SoapObject) object
                .getProperty("getDomesticAirlinesTimeResult");
        SoapObject airLinesSoapObject=(SoapObject)((SoapObject)airLinesTimeSoapObject.getProperty(1))
                .getProperty(0);

        HashMap<String, String> mMap=new HashMap<String, String>();
        mMap.put("航空公司", "航空公司");
        mMap.put("出發時間", "出發時間");
        mMap.put("到達時間", "到達時間");
        mMap.put("出發機場", "出發機場");
        mMap.put("到達機場", "到達機場");
        flights.add(mMap);
        for(int i=0;i<airLinesSoapObject.getPropertyCount();i++)
        {
            SoapObject airLineSoapObject=(SoapObject) airLinesSoapObject.getProperty(i);
            HashMap<String, String> flightHashMap=new HashMap<String, String>();
            flightHashMap.put("航空公司",airLineSoapObject.getProperty("Company") .toString());
            flightHashMap.put("出發機場",airLineSoapObject.getProperty("StartDrome") .toString());
            flightHashMap.put("到達機場",airLineSoapObject.getProperty("ArriveDrome") .toString());
            flightHashMap.put("出發時間",airLineSoapObject.getProperty("StartTime") .toString());
            flightHashMap.put("到達時間",airLineSoapObject.getProperty("ArriveTime") .toString());
            flights.add(flightHashMap);
        }
        return flights;
    }

    public static ArrayList<HashMap<String, String>> getTrainTimeList(String startStation,String arriveStation) 
    {
        methodName = "getStationAndTimeByStationName";
        endPoint = "http://webservice.webxml.com.cn/WebServices/TrainTimeWebService.asmx";
        soapAction = NAMESPACE + methodName;

        ArrayList<HashMap<String, String>> trains=new ArrayList<HashMap<String, String>>();
        SoapObject rpc = new SoapObject(NAMESPACE, methodName);
        // 設置需調用WebService接口需要傳入的兩個參數mobileCode、userId,不可以隨便寫,必須和提供的參數名相同
        rpc.addProperty("StartStation", startStation);
        rpc.addProperty("ArriveStation", arriveStation);
        rpc.addProperty("UserID", "你的ID");
        // 生成調用WebService方法的SOAP請求信息,並指定SOAP的版本
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.bodyOut = rpc;
        // 設置是否調用的是dotNet開發的WebService
        envelope.dotNet = true;
        HttpTransportSE transport = new HttpTransportSE(endPoint);

        // 調用WebService
        try {
            transport.call(soapAction, envelope);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 獲取返回的數據
        SoapObject object = (SoapObject) envelope.bodyIn;
        SoapObject trainsSoapObject = (SoapObject) object
                .getProperty("getStationAndTimeByStationNameResult");
        SoapObject trainsTimeSoapObject=(SoapObject)((SoapObject)trainsSoapObject.getProperty(1))
                .getProperty(0);

        HashMap<String, String> mMap=new HashMap<String, String>();
        mMap.put("車次", "車次");
        mMap.put("出發時間", "出發時間");
        mMap.put("到達時間", "到達時間");
        mMap.put("時長", "時長");
        trains.add(mMap);
        for(int i=0;i<trainsTimeSoapObject.getPropertyCount();i++)
        {
            SoapObject trainTimeSoapObject=(SoapObject) trainsTimeSoapObject.getProperty(i);
            HashMap<String, String> trainHashMap=new HashMap<String, String>();
            trainHashMap.put("車次",trainTimeSoapObject.getProperty("TrainCode") .toString());
            trainHashMap.put("出發時間",trainTimeSoapObject.getProperty("StartTime") .toString());
            trainHashMap.put("到達時間",trainTimeSoapObject.getProperty("ArriveTime") .toString());
            trainHashMap.put("時長",trainTimeSoapObject.getProperty("UseDate") .toString());
            trains.add(trainHashMap);
        }
        return trains;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章