如何解析 http 异常 401 上的成功正文响应?
How to parse success body response on http exception 401?
即使服务器 returns 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
class,它是您的响应对象的包装器,它包含您的响应数据和错误主体以及成功状态,所以不用做 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.
}
即使服务器 returns 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
class,它是您的响应对象的包装器,它包含您的响应数据和错误主体以及成功状态,所以不用做 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.
}