我正在使用翻新。使用Kotlin。我需要知道共振状态代码。像是200还是500。如何从响应中获取?
我的Api类:
interface Api {
@POST("user/code/check")
fun checkSmsCode(@Body body: CheckCodeBody): Single<Response<Void>> }
这就是我给Api打电话的方式。但是请注意,SERVE不会在响应主体中返回代码字段!
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中实现呢?
答案 0 :(得分:0)
所以您的响应应该看起来像这样
override fun onResponse(call: Call<MyModel>?, response: Response<MyModel>?) {
//
}
})
然后在里面,您应该就能做到
override fun onResponse(call: Call<MyModel>?, response: Response<MyModel>?) {
response.code()
}
})
这是你在说什么吗?
答案 1 :(得分:0)
如果您尚未配置改造请求方法以返回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
})
答案 2 :(得分:0)
您需要使用它
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
})