如何在 http 异常 401 上解析成功正文响应?



即使服务器返回 401 HTTP 异常,我也试图解析实际的响应正文。

protected inline fun <RESPONSE : ParentResponse> executeNetworkCall(
crossinline request: () -> Single<RESPONSE>,
crossinline successful: (t: RESPONSE) -> Unit,
crossinline error: (t: RESPONSE) -> Unit) {
request().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ t: RESPONSE ->
errorHandler!!.checkApiResponseError(t)?.let {
listener?.onErrorWithId(t.message!!)
error(t)
return@subscribe
}
successful(t)
}
,
{ t: Throwable ->
listener?.onErrorWithId(t.message!!)
}
)
}

这就是我写的。当响应和错误以通常的方式分开时,它可以很好地解析响应和错误。但是我想在收到 401 HTTP 异常时解析成功响应。

提前谢谢..

使用 401 HTTP 的响应如下所示。

401 Unauthorized - HTTP Exception 
{"Message":"Authentication unsuccessful","otherData":"//Some data"}

顺便说一下,我必须检查HTTP错误代码。

if (statusCode==401){
print("Authentication unsuccessful")
}

您可以使用Retrofit 的Response类来实现此目的,它是响应对象的包装器,它既有响应的数据和错误正文,也有成功状态,因此无需执行Single<RESPONSE>使用Single<Response<RESPONSE>>

解析响应对象可以是这样的:

{ t: Response<RESPONSE> ->
if (t.isSuccessful())
// That's the usual success scenario
else
// You have a response that has an error body.
}
,
{ t: Throwable ->
// You didn't reach the endpoint somehow, maybe a timeout or an invalid URL.
}

最新更新