SOAP協(xié)議之Retrofit解析

一、前言

最近公司需要對接webservice的服務(wù)器接口,從而給了時間研究webservice的內(nèi)部協(xié)議。webservice中用到的是soap協(xié)議,簡單來說,soap協(xié)議就是http協(xié)議+XML格式,它是RPC調(diào)用的一種。Android中的主流http請求框架用的是OKhttp,請求解耦框架是Retrofit。既然soap是基于http協(xié)議的,那么通過Retrofit框架處理是沒有問題的。

soap即簡單的面向?qū)ο髤f(xié)議,類比onc rpc是一個基于二進(jìn)制的調(diào)用,這并不利于擴(kuò)展,所以之后才有了面向?qū)ο蟮膕oap協(xié)議,在XML中參數(shù)的順序和增加并不會對之前的代碼有所影響。

在網(wǎng)上找了些Retrofit封裝代碼,比較好比較入門的https://github.com/xiewenfeng/RetorfitWebServiceSample,本文也是在此基礎(chǔ)上分析完善。

二、SOAP協(xié)議

1)、WebService請求協(xié)議

POST http://www.webxml.com.cn/WebServices/WeatherWebService.asmx HTTP/1.1
Content-Type: text/xml;charset=UTF-8
Content-Length: 347
SOAPAction: http://WebXml.com.cn/getWeatherbyCityName

 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
   <soap:Body xmlns="http://WebXml.com.cn/">
      <getWeatherbyCityName>
          <theCityName>合肥</theCityName>
       </getWeatherbyCityName>
    </soap:Body>
 </soap:Envelope>

從webservice發(fā)送的協(xié)議來看,很容易看出,它是基于Http協(xié)議的,增加了header字段SOAPAction,以及將文本類型改成Content-Type: text/xml;charset=UTF-8。這樣就能告訴服務(wù)器,參數(shù)類型是XML,以及調(diào)用哪個方法解析。

下面再來看看SOAP的語法結(jié)構(gòu):

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Header>
  ...
  ...
</soap:Header>

<soap:Body>
  ...
  ...
  <soap:Fault>
    ...
    ...
  </soap:Fault>
</soap:Body>

</soap:Envelope>

從SOAP結(jié)構(gòu)中可以看到有四大塊:

  • Envelope必選,可把此 XML 文檔標(biāo)識為一條 SOAP 消息
  • Header可選,頭部信息附屬功能
  • Body必選,調(diào)用信息(傳遞的參數(shù))或者響應(yīng)信息(返回的結(jié)果)
  • Fault可選,提供有關(guān)在處理此消息所發(fā)生錯誤的信息

Envelope

Envelope為根元素,沒有該元素的一律不會是SOAP消息。

其中soap:Envelope中的soap是根據(jù)xmlns:soap="http://www.w3.org/2003/05/soap-envelope"而來的,它們必須一一匹配。

Body

Body元素在請求時放入傳遞給服務(wù)器的參數(shù),返回時是服務(wù)器返回的數(shù)據(jù)。

2)、WebService返回協(xié)議

先看下上面的請求的返回例子:

        200 OK http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
        Content-Length: 3229
        Content-Type: application/soap+xml; charset=utf-8
        Server: Microsoft-IIS/7.5
        X-AspNet-Version: 2.0.50727
        X-Powered-By: ASP.NET
        Date: Sun, 05 May 2019 07:11:36 GMT
        OkHttp-Sent-Millis: 1557040300871
        OkHttp-Received-Millis: 1557040300923
        <?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <soap:Body>
                <getWeatherbyCityNameResponse xmlns="http://WebXml.com.cn/">
                    <getWeatherbyCityNameResult>
                        <string>安徽</string>
                        <string>合肥</string>
                        <string>58321</string>
                        <string>58321.jpg</string>
                        <string>2019/5/5 14:51:16</string>
                        <string>15℃/28℃</string>
                        <string>5月5日 多云</string>
                        <string>東風(fēng)3-4級轉(zhuǎn)東北風(fēng)小于3級</string>
                        <string>1.gif</string>
                        <string>1.gif</string>
                        <string>今日天氣實況:氣溫:27℃;風(fēng)向/風(fēng)力:東北風(fēng) 3級;濕度:46%;紫外線強(qiáng)度:弱。空氣質(zhì)量:良。</string>
                        <string>紫外線指數(shù):弱,輻射較弱,涂擦SPF12-15、PA+護(hù)膚品。
                                健臻·血糖指數(shù):易波動,血糖易波動,注意監(jiān)測。
                                穿衣指數(shù):舒適,建議穿長袖襯衫單褲等服裝。
                                洗車指數(shù):較適宜,無雨且風(fēng)力較小,易保持清潔度。
                                空氣污染指數(shù):良,氣象條件有利于空氣污染物擴(kuò)散。</string>
                        <string>12℃/23℃</string>
                        <string>5月6日 多云</string>
                        <string>東風(fēng)3-4級轉(zhuǎn)小于3級</string>
                        <string>1.gif</string>
                        <string>1.gif</string>
                        <string>13℃/20℃</string>
                        <string>5月7日 多云轉(zhuǎn)小雨</string>
                        <string>東風(fēng)小于3級</string>
                        <string>1.gif</string>
                        <string>7.gif</string>
                        <string>合肥市,古稱廬州,又名廬陽,位于安徽省中部,地處江淮之間、巢湖北岸,轄東市、西市、中市、郊區(qū)4區(qū)和長豐、肥東、肥西3縣??偯娣e7266平方公里,人口425.9萬。市內(nèi)道路寬闊,綠樹成蔭,景色優(yōu)美,既多現(xiàn)代建筑,又有名勝古跡,是一座古老而又年青的城市。合肥市位于江淮之間,處于中緯度地帶,為亞熱帶濕潤季風(fēng)氣候。年平均氣溫在15℃-16℃之間,極端最低氣溫-20.6℃,極端最高氣溫38℃以上。年平均降水量在900-1000毫米之間。全年氣溫變化的特點是季風(fēng)明顯、四季分明、氣候溫和、雨量適中、春溫多變、秋高氣爽、梅雨顯著、夏雨集中,總之氣候條件優(yōu)越,氣候資源豐富。合肥市素以“三國舊地、包拯故里”聞名于世,具有“淮右襟喉、江南唇齒”的戰(zhàn)略地位,常為兵家必爭之地。三國時魏將張遼大敗孫權(quán)十萬大軍的逍遙津戰(zhàn)役,即發(fā)生在這里。兩千多年前,這里就已開始形成商業(yè)都會。秦、漢在此設(shè)郡縣,明、清為廬州府治,民國時為安徽省省會,如今已是千檣鱗次、商賈輻湊的商業(yè)都會。合肥素有“綠色城市”、“花園城市”的美名,其環(huán)城公園便修建在合肥古城墻的基礎(chǔ)之上,沿著起伏的崗丘地形,加之原有的綠林帶及護(hù)城河,精筑而成。環(huán)城公園總長約達(dá)9公里,分為六個景區(qū),其中較為著名的有茂林修竹,夏河朝露的銀河景區(qū);湖巒相映、水碧楓赤的西山景區(qū);林木蔥蘢、芳草常青的環(huán)北景區(qū)。這樣的環(huán)城公園無城墻之隔閡,面水而立,一派迷人旖旎的江南風(fēng)光。</string>
                    </getWeatherbyCityNameResult>
                </getWeatherbyCityNameResponse>
            </soap:Body>
        </soap:Envelope>

從返回的可以看出來它是包含了以上的Envelope和Body,解析只需要將XML格式化成對象格式即可。

小結(jié)

從以上的協(xié)議分析,使用Retrofit請求和解析沒有任何問題。請求的是Post請求,現(xiàn)在將請求的消息按照SOAP協(xié)議封裝成符合服務(wù)器要求的格式,再將其字符串注入到post請求的Body中即可。返回的消息是個XML格式的字符串,現(xiàn)在只需要按照后臺給定的消息去解析即可,也可以通過XML解析框架處理,這會更加簡單。

三、實踐Retrofit解析

引用的第三方庫:

  • retrofit :網(wǎng)絡(luò)請求框架
  • logging-interceptor : OKhttp日志打印
  • converter-simplexml : 生成及解析XML框架

1)、請求參數(shù)編寫

 <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
   <soap:Body xmlns="http://WebXml.com.cn/">
      <getWeatherbyCityName>
          <theCityName>合肥</theCityName>
       </getWeatherbyCityName>
    </soap:Body>
 </soap:Envelope>

需要我們將代碼拼接成如上的格式,其中theCityName里面的內(nèi)容是傳入的。

為此使用了converter-simplexml框架將對象封裝成XML,建立了三個類。

// Root代表外層
@Root(name = "soap:Envelope")
@NamespaceList({
        @Namespace(reference = "http://www.w3.org/2001/XMLSchema-instance", prefix = "xsi"),
        @Namespace(reference = "http://www.w3.org/2001/XMLSchema", prefix = "xsd"),
        @Namespace(reference = "http://www.w3.org/2003/05/soap-envelope", prefix = "soap")
})
public class RequestEnvelope {
    @Element(name = "soap:Body")
    private RequestBody requestBody;

    public void setRequestBody(RequestBody requestBody) {
        this.requestBody = requestBody;
    }
}
@NamespaceList({
        @Namespace(reference = "http://WebXml.com.cn/")
})
public class RequestBody {

    @Element(name = "getWeatherbyCityName")
    private RequestModel getWeatherbyCityName;

    public void setGetWeatherbyCityName(RequestModel getWeatherbyCityName) {
        this.getWeatherbyCityName = getWeatherbyCityName;
    }
}
/**
 * 描述:參數(shù)
 * Created by PHJ on 2019/5/5.
 */
public class RequestModel {

    @Element(name = "theCityName")
    public String cityName;     //城市名字


    public void setCityName(String cityName) {
        this.cityName = cityName;
    }
}

以此轉(zhuǎn)化,就是所需要的XML。并將XML放入到請求體即可。

2)、解析響應(yīng)信息

        200 OK http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
        Content-Length: 3229
        Content-Type: application/soap+xml; charset=utf-8
        Server: Microsoft-IIS/7.5
        X-AspNet-Version: 2.0.50727
        X-Powered-By: ASP.NET
        Date: Sun, 05 May 2019 07:11:36 GMT
        OkHttp-Sent-Millis: 1557040300871
        OkHttp-Received-Millis: 1557040300923
        <?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <soap:Body>
                <getWeatherbyCityNameResponse xmlns="http://WebXml.com.cn/">
                    <getWeatherbyCityNameResult>
                        <string>安徽</string>
                        <string>合肥</string>
                        <string>58321</string>
                        <string>58321.jpg</string>
                        <string>2019/5/5 14:51:16</string>
                        <string>15℃/28℃</string>
                        <string>5月5日 多云</string>
                        <string>東風(fēng)3-4級轉(zhuǎn)東北風(fēng)小于3級</string>
                        <string>1.gif</string>
                        <string>1.gif</string>
                        <string>今日天氣實況:氣溫:27℃;風(fēng)向/風(fēng)力:東北風(fēng) 3級;濕度:46%;紫外線強(qiáng)度:弱??諝赓|(zhì)量:良。</string>
                        <string>紫外線指數(shù):弱,輻射較弱,涂擦SPF12-15、PA+護(hù)膚品。
                                健臻·血糖指數(shù):易波動,血糖易波動,注意監(jiān)測。
                                穿衣指數(shù):舒適,建議穿長袖襯衫單褲等服裝。
                                洗車指數(shù):較適宜,無雨且風(fēng)力較小,易保持清潔度。
                                空氣污染指數(shù):良,氣象條件有利于空氣污染物擴(kuò)散。</string>
                        <string>12℃/23℃</string>
                        <string>5月6日 多云</string>
                        <string>東風(fēng)3-4級轉(zhuǎn)小于3級</string>
                        <string>1.gif</string>
                        <string>1.gif</string>
                        <string>13℃/20℃</string>
                        <string>5月7日 多云轉(zhuǎn)小雨</string>
                        <string>東風(fēng)小于3級</string>
                        <string>1.gif</string>
                        <string>7.gif</string>
                        <string>合肥市,古稱廬州,又名廬陽,位于安徽省中部,地處江淮之間、巢湖北岸,轄東市、西市、中市、郊區(qū)4區(qū)和長豐、肥東、肥西3縣。總面積7266平方公里,人口425.9萬。市內(nèi)道路寬闊,綠樹成蔭,景色優(yōu)美,既多現(xiàn)代建筑,又有名勝古跡,是一座古老而又年青的城市。合肥市位于江淮之間,處于中緯度地帶,為亞熱帶濕潤季風(fēng)氣候。年平均氣溫在15℃-16℃之間,極端最低氣溫-20.6℃,極端最高氣溫38℃以上。年平均降水量在900-1000毫米之間。全年氣溫變化的特點是季風(fēng)明顯、四季分明、氣候溫和、雨量適中、春溫多變、秋高氣爽、梅雨顯著、夏雨集中,總之氣候條件優(yōu)越,氣候資源豐富。合肥市素以“三國舊地、包拯故里”聞名于世,具有“淮右襟喉、江南唇齒”的戰(zhàn)略地位,常為兵家必爭之地。三國時魏將張遼大敗孫權(quán)十萬大軍的逍遙津戰(zhàn)役,即發(fā)生在這里。兩千多年前,這里就已開始形成商業(yè)都會。秦、漢在此設(shè)郡縣,明、清為廬州府治,民國時為安徽省省會,如今已是千檣鱗次、商賈輻湊的商業(yè)都會。合肥素有“綠色城市”、“花園城市”的美名,其環(huán)城公園便修建在合肥古城墻的基礎(chǔ)之上,沿著起伏的崗丘地形,加之原有的綠林帶及護(hù)城河,精筑而成。環(huán)城公園總長約達(dá)9公里,分為六個景區(qū),其中較為著名的有茂林修竹,夏河朝露的銀河景區(qū);湖巒相映、水碧楓赤的西山景區(qū);林木蔥蘢、芳草常青的環(huán)北景區(qū)。這樣的環(huán)城公園無城墻之隔閡,面水而立,一派迷人旖旎的江南風(fēng)光。</string>
                    </getWeatherbyCityNameResult>
                </getWeatherbyCityNameResponse>
            </soap:Body>
        </soap:Envelope>

解析XML就是去除外層的包裝,轉(zhuǎn)化成對象,并且保存。

在此之前需要配置轉(zhuǎn)化格式:

    private static Strategy strategy = new AnnotationStrategy();
    private static Serializer serializer = new Persister(strategy);

        // 設(shè)置電腦鏈接
        instance.retrofit = builder.baseUrl(BASE_URL)
                // 設(shè)置client
                .client(client)
                // 設(shè)置Json解析器
                .addConverterFactory(SimpleXmlConverterFactory.create(serializer))
                .build();

采用了SimpleXmlConverterFactory解析對應(yīng)的XML,當(dāng)然這部分也可以自己獲取字符串后自己解析。

詳細(xì)代碼可以參考GitHub代碼

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容