如何使用 Retrofit2 获取带有邮政编码 JSON 正文的地址列表



我是第一次使用 Retrofit2,所以我对如何继续感到困惑。我有以下代码

fun getAddressFromPostCode(postCode: String): List<PXAddress>{
val trimmedPostCode = postCode.replace("\s".toRegex(),"").trim()
val dataBody = JSONObject("""{"postCode":"$trimmedPostCode"}""").toString()
val hmac = HMAC()
val hmacResult = hmac.sign(RequestConstants.CSSecretKey, dataBody)
val body = JSONObject("""{"data":"$dataBody", "data_signature":"$hmacResult"}""").toString()
val url = RequestConstants.getAddress
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(url)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
val address: PXAddress = retrofit.create(PXAddress::class.java)
}

身体需要看起来像这样:

"数据":{ "邮政编码": "WA1 1LD" }, "data_signature": "{{getSignature}}" }

并且响应应该是

"成功": 1, "地址":[ { "地址1": "博物馆街47号", "地址 2":空, "地址 3":空, "镇": "沃灵顿", "县": ", "邮政编码": "WA1 1LD" }, { "地址1": "博物馆街49a号", "地址 2":空, "地址 3":空, "镇": "沃灵顿", "县": ", "邮政编码": "WA1 1LD" }, { "地址1": "丽达招聘", "地址2": "博物馆街49号", "地址 3":空, "镇": "沃灵顿", "县": ", "邮政编码": "WA1 1LD" } ] }

我需要将该响应转换为PXAddress列表,即

open class PXAddress : RealmObject() {
var addressLine1: String? = null
var addressLine2: String? = null
var addressLine3: String? = null
var town: String? = null
var county: String? = null
var postcode: String? = null
}

由于某些原因,您的实现是错误的:

  1. 使用接口定义 Web 服务请求,必须定义如下所示的类:
interface ApiService {
@POST("your/webservice/path")
fun getPXAddress(@Body dataBody: YourBodyModel): Call<List<PXAddress>>
}
    你必须
  1. 使用数据类作为主体来调用你的 Web 服务,gson 转换器会用 json 转换你的模型,在你的主代码中你必须这样做:
fun getAddressFromPostCode(postCode: String): List<PXAddress>{
val trimmedPostCode = postCode.replace("\s".toRegex(),"").trim()
val dataBody = DataBodyObject(postCode = trimmedPostCode)
val hmac = HMAC()
val hmacResult = hmac.sign(RequestConstants.CSSecretKey, dataBody)
val yourBodyModel = YourBodyModel(data = dataBody, data_signature = hmacResult)
val url = RequestConstants.getUrl() // This address must be only the host, the path is specified in ApiService interface
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build()
val api: ApiService = retrofit.create(ApiService::class.java) // With this you create a instance of your apiservice
val myCall: Call<List<PXAddress>> = api.getPXAddress(yourBodyModel) //with this you can call your service synchronous
}
  1. 最后一件事,你必须使用 rxjava、livedata 或协程调用你的方法异步模式。所有这些都提供要改造的转换器。默认情况下,retrofit 有一个调用方法,如我向您展示的示例,您可以完成代码:
myCall.enqueue(object : Callback<List<PXAddress>> {
override fun onFailure(call: Call<List<PXAddress>>?, t: Throwable?) {
// Error response
}
override fun onResponse(call: Call<List<PXAddress>>?, response: Response<List<PXAddress>>?) {
// Success response
val myList : List<PXAddress> = response?.body
}
})

此致敬意!

最新更新