Retrofit WebService 实践

发布一下 0 0


前言

作为 Android 开发,平时和后端聊得最多的除了喝酒就是接口。常用语:RestfulWebService,前者现在聊得多,后者以前聊得多。

默认含义分别为:

  • Restful:HTTP 协议 和 JSON 格式
  • WebService:特指 Soap 协议 和 XML 格式

针对基于 HTTP 协议且格式为 JSON 的 Restful 接口,Android 客户端一般采用 Retrofit + Gson/Moshi 的方案解决。

而针对 Soap 协议 和 XML 格式的 Soap WebService ,则少有实践机会。考虑到 Retroift is A type-safe HTTP client for Android and Java. 并且 Soap 协议是基于 XML 且通过 HTTP 协议来交换信息,故解决好 XML 的封装与解析,使用 Retrofit 实现 SOAP 服务调用应该简单。

Restful & WebService

概念

WebService

WebService 是一个平台独立的,低耦合的,自包含的、基于可编程的 WEB 应用程序,可使用开放的 XML(标准通用标记语言下的一个子集)标准来描述、发布、发现、协调和配置这些应用程序,用于开发分布式的交互操作的应用程序[1]。

WebService 三要素:

  • SOAP(Simple Object Access Protocol):描述传递信息的格式;
  • WSDL(WebServicesDescriptionLanguage):描述如何访问具体的接口;
  • UDDI(UniversalDescriptionDiscovery andIntegration):管理,分发,查询 WebService 。

SOAP

SOAP(Simple Object Access Protocol),即简单对象访问协议,是交换数据的一种协议规范,是一种轻量的、简单的、基于XML(标准通用标记语言下的一个子集)的协议,它被设计成在WEB上交换结构化的和固化的信息。

  • SOAP 指简易对象访问协议
  • SOAP 是一种通信协议
  • SOAP 用于应用程序之间的通信
  • SOAP 是一种用于发送消息的格式
  • SOAP 被设计用来通过因特网进行通信
  • SOAP 独立于平台
  • SOAP 独立于语言
  • SOAP 基于 XML
  • SOAP 很简单并可扩展
  • SOAP 允许您绕过防火墙
  • SOAP 将被作为 W3C 标准来发展[2]

SOAP 消息的基本结构

<?xml version="1.0"?><soap:Envelopexmlns: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>

SoapUI

 soapUI,是一款开源软件测试工具。

   开源软件,是源码可以被公众使用的软件,并且此软件的使用,修改和分发也不受许可证的束缚。

  软件测试工具,即是通过一些工具能够使软件的一些简单问题直观的显示在读者的面前的软件工具。它们使测试人员能够更好地找出软件错误的所在。

  soapUI是一款开源测试工具,通过soap/http来检查、调用、实现Web Service的功能/负载/符合性测试。该工具既可作为一个单独的测试软件使用,也可利用附件集成到Eclipse,maven2.X,Netbeans 和 intellij 中使用。

WebXml

WEB服务开发、WEBXML是标准商业和免费WEB服务(Web Service)提供商您可以在这里搜索技术问题的答案以及获取最新的发展动态。数据库开发和网站设计开发的解决方案和技术支持WEB服务接入、从事WEB服务设计

实践

通过 Retrofit 调用 Web Xml 网站 的 国内手机号码归属地查询WEB服务。

  • SOAP 协议
  • XML 格式
  • Kotlin + Retrofit + Coroutine

1. 接口分析

Retrofit WebService 实践

MobileCodeWS

Retrofit WebService 实践

SoapUI MobileCodeWS

针对 SOAP 1.1SOAP 1.2 协议,虽然请求报文略有不用,但是请求结果报文相同,SOAP 协议HTTP POST 请求且 Content-Type: text/xml; charset=utf-8。当然,若嫌 SOAP 协议麻烦,可以直接利用参数进行 GET 或者 POST 的请求,省去封装 XML 的麻烦。

Retrofit WebService 实践

HTTP GET and POST

2. 程序设计

2.1 添加依赖

dependencies {    implementation fileTree(include: ['*.jar'], dir: 'libs')    implementation 'androidx.appcompat:appcompat:1.4.0'    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'    implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.2'    implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.2'    implementation 'com.squareup.retrofit2:retrofit:2.9.0'    implementation 'com.squareup.retrofit2:converter-simplexml:2.3.0'    implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'    implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'    implementation 'com.github.kirich1409:viewbindingpropertydelegate:1.5.6'}

2.2 请求接口

  • GET
  • POST
  • POST SOAP 1.1(构建请求对象和响应对象)
  • POST SOAP 1.2(拼接 XML )
interface MobileCodeApi {    @Headers("Content-Type: text/xml; charset=utf-8")    @GET("MobileCodeWS.asmx/getMobileCodeInfo")    suspend fun mobileCodeInfoByHttpGet(        @Query("mobileCode") mobileCode: String,        @Query("userID") userId: String = ""    ): ResponseBody    @POST("MobileCodeWS.asmx/getMobileCodeInfo")    @FormUrlEncoded    suspend fun mobileCodeInfoByHttpPost(        @Field("mobileCode") mobileCode: String,        @Field("userID") userId: String = ""    ): ResponseBody    @Headers("Content-Type: text/xml;charset=utf-8")    @POST("MobileCodeWS.asmx")    suspend fun mobileCodeInfoBySoap11(        @Body requestEnvelope: MobileCodeRequestEnvelope?    ): MobileCodeResponseEnvelope    @Headers("Content-Type: application/soap+xml;charset=utf-8")    @POST("MobileCodeWS.asmx")    suspend fun mobileCodeInfoBySoap12(        @Body requestEnvelope: RequestBody    ): ResponseBody}

2.3 请求体设计

SOAP 1.1 协议

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://WebXml.com.cn/">   <soapenv:Header/>   <soapenv:Body>      <web:getMobileCodeInfo>         <!--Optional:-->         <web:mobileCode></web:mobileCode>         <!--Optional:-->         <web:userID></web:userID>      </web:getMobileCodeInfo>   </soapenv:Body></soapenv:Envelope>

查看请求体 XML 模板,总共 4 层,我们定义 3 个类即可满足。

核心为 com.squareup.retrofit2:converter-simplexml:2.3.0 依赖库中的注解。

MobileCodeRequestEnvelope.kt

@Root(name = "soapenv:Envelope")@NamespaceList(    Namespace(prefix = "soapenv", reference = "http://schemas.xmlsoap.org/soap/envelope/"),    Namespace(prefix = "web", reference = "http://WebXml.com.cn/"))class MobileCodeRequestEnvelope {    @field:Element(name = "soapenv:Body", required = true)    var body: MobileCodeRequestBody? = null}

MobileCodeRequestBody.kt

@Root(name = "soapenv:Body")class MobileCodeRequestBody {    @field:Element(name = "web:getMobileCodeInfo", required = true)    var mobileCodeRequestData: MobileCodeRequestData? = null}

MobileCodeRequestData.kt

@Root(name = "getMobileCodeInfo")class MobileCodeRequestData {    @field:Element(name = "web:mobileCode", required = true)    var mobileCode: String? = null    @field:Element(name = "web:userID", required = true)    var userId: String = ""}

2.4 响应体设计

SOAP 1.1 协议

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">   <soap:Body>      <getMobileCodeInfoResponse xmlns="http://WebXml.com.cn/">         <getMobileCodeInfoResult>18507152743:湖北 武汉 湖北联通GSM卡</getMobileCodeInfoResult>      </getMobileCodeInfoResponse>   </soap:Body></soap:Envelope>

参考请求体,我们定义 3 个类即可满足响应体设计需求。

MobileCodeResponseEnvelope.kt

@Root(name = "soap:Envelope")@NamespaceList(    Namespace(prefix = "soap", reference = "http://www.w3.org/2003/05/soap-envelope"),    Namespace(prefix = "xsi", reference = "http://www.w3.org/2001/XMLSchema-instance"),    Namespace(prefix = "xsd", reference = "http://www.w3.org/2001/XMLSchema"))class MobileCodeResponseEnvelope {    @field:Element(name = "Body")    var body: MobileCodeResponseBody? = null}

MobileCodeResponseBody.kt

@Root(name = "Body")class MobileCodeResponseBody {    @field:Element(name = "getMobileCodeInfoResponse", required = false)    var response: MobileCodeInfoResponse? = null}

MobileCodeResponse.kt

@Root(name = "getMobileCodeInfoResponse", strict = false)class MobileCodeInfoResponse {    @field:Element(name = "getMobileCodeInfoResult", required = false)    var mobileCodeInfoResult: String? = null}

2.5 Retrofit

object Retrofitance {    private const val BASE_URL = "http://ws.webxml.com.cn/WebServices/"    private val strategy: Strategy = AnnotationStrategy()    private val serializer: Serializer = Persister(strategy)    private val client = OkHttpClient.Builder()        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))        .build()    private val retrofitance = Retrofit.Builder()        .client(client)        .addConverterFactory(SimpleXmlConverterFactory.create(serializer))        .baseUrl(BASE_URL)        .build()    val mobileCodeApi: MobileCodeApi = retrofitance.create(MobileCodeApi::class.java)}

2.6 请求数据

2.6.1 GET

fun doHttpGet() {    lifecycleScope.launchWhenCreated {        val response =            Retrofitance.mobileCodeApi.mobileCodeInfoByHttpGet(binding.etMobile.text.toString())        Toast.makeText(context, "请求成功", Toast.LENGTH_SHORT).show()        val result = response.string()        binding.tvMobileResult.text = result    }}

2.6.2 POST

fun doHttpPost() {    lifecycleScope.launchWhenCreated {        val response =            Retrofitance.mobileCodeApi.mobileCodeInfoByHttpPost(binding.etMobile.text.toString())        Toast.makeText(context, "请求成功", Toast.LENGTH_SHORT).show()        val result = response.string()        binding.tvMobileResult.text = result    }}

2.6.3 SOAP 1.1

fun doSoap11() {    val apiService = Retrofitance.mobileCodeApi    val requestEnvelope = MobileCodeRequestEnvelope()    val requestBody = MobileCodeRequestBody()    val requestData = MobileCodeRequestData()    requestData.mobileCode = binding.etMobile.text.toString()    requestBody.mobileCodeRequestData = requestData    requestEnvelope.body = requestBody    lifecycleScope.launchWhenCreated {        val mobileCodeResponseEnvelope = apiService.mobileCodeInfoBySoap11(requestEnvelope)        Toast.makeText(context, "请求成功", Toast.LENGTH_SHORT).show()        val result = mobileCodeResponseEnvelope.body?.response?.mobileCodeInfoResult        binding.tvMobileResult.text = result    }}

2.6.3 SOAP 1.2

为了区分请求形式,直接采用 XML String 作为 RequestBody,也省事。

fun doSoap12() {    val xml = """        <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:web="http://WebXml.com.cn/">           <soap:Header/>           <soap:Body>              <web:getMobileCodeInfo>                 <web:mobileCode>${binding.etMobile.text}</web:mobileCode>                 <web:userID></web:userID>              </web:getMobileCodeInfo>           </soap:Body>        </soap:Envelope>    """.trimIndent()    lifecycleScope.launchWhenCreated {        val result =            Retrofitance.mobileCodeApi.mobileCodeInfoBySoap12(xml.toRequestBody("text/xml".toMediaTypeOrNull()))        Toast.makeText(context, "请求成功", Toast.LENGTH_SHORT).show()        binding.tvMobileResult.text = result.string()    }}

2.7 效果

Retrofit WebService 实践

3. 源码

https://github.com/onlyloveyd/RetrofitWebService

参考资料

[1]WebService百度百科: https://baike.baidu.com/item/Web%20Service

[2]什么是 Soap?: https://www.w3school.com.cn/soap/soap_intro.asp

[3]SoapUI: https://www.soapui.org/

[4]WebXml服务: http://www.webxml.com.cn/

Retrofit WebService 实践

版权声明:内容来源于互联网和用户投稿 如有侵权请联系删除

本文地址:http://0561fc.cn/69767.html