0

即使服务器返回 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")
}
4

1 回答 1

1

您可以为此目的使用 Retrofit 的Response类,它是响应对象的包装器,它既有响应的数据和错误主体,也有成功状态,所以不要Single<RESPONSE>使用 use 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.
}
于 2018-09-08T03:31:55.067 回答