我正在使用改造。使用科特林。我需要知道响应状态代码。比如是 200 还是 500。我怎样才能从回复中得到它?
我的 Api 类:
interface Api {
@POST("user/code/check")
fun checkSmsCode(@Body body: CheckCodeBody): Single<Response<Void>> }
这就是我调用 Api 的方式。但请注意,服务不会在响应正文中返回代码字段!
api.checkSmsCode(
CheckCodeBody(
code = code
)
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
//HOW TO CHECK STATUS RESPONSE STATUS CODE HERE???
},
{ e ->
when (e) {
is IOException -> view?.showNoNetworkAlert()
else -> view?.invalidCodeError()
}
}
).also {}
据我了解,在 Java 中这是一件很容易的事情。
你只需使用
response.code()
或类似的东西就可以了。但在 Kotlin 中如何实现呢?
所以你的回应应该是这样的
override fun onResponse(call: Call<MyModel>?, response: Response<MyModel>?) {
//
}
})
然后在里面你应该能够做到
override fun onResponse(call: Call<MyModel>?, response: Response<MyModel>?) {
response.code()
}
})
这就是你所说的吗?
你需要使用它
interface OnlineStoreService{
@Headers("Content-Type: application/json","Connection: close")
@POST
fun getDevices(
@Url url: String,
@Header("Authorization") token: String,
@Body apiParams: APIParams
): Observable<OnlineStoresInfo>
}
.subscribe({ onlineStoresInfo -> // or it -> where "it" it's your object response, in this case is my class OnlineStoresInfo
loading.value = false
devices.value = onlineStoresInfo.devices
}, { throwable ->
Log.e(this.javaClass.simpleName, "Error getDevices ", throwable)
loading.value = false
error.value = context.getString(R.string.error_information_default_html)
})
.subscribe({ it ->
// code
}, { throwable ->
//code
})
如果您尚未将改造请求方法配置为返回
Response<*>
,您将无法获得响应代码。示例:
interface SomeApi{
@POST("user/code/check")
fun checkSmsCode(@Body body: CheckCodeBody): Single<Response<String>>
}
完成请求后:
.subscribe({
//access response code here like : it.code()
//and you can access the response.body() for your data
//also you can ask if that response.isSuccessful
})