Retrofit2使用RxJava的Observable概念处理HTTP 204(无内容响应)情况 [英] Retrofit2 handling HTTP 204 (No Content response ) situation with RxJava's Observable concepts
问题描述
我有一个Web服务,该服务返回一个主题的用户列表,如果该主题没有任何用户,则仅返回HTTP代码204(无内容).
I have a web-service which return a list of users for a topic, if there is no any user for that topic it just returns HTTP code 204( No Content).
这是我为此服务(在Kotlin中)进行的retrofit2呼叫
This is my retrofit2 call for that service (in Kotlin)
@GET("/user/{topic}")
fun getAllUserFor(@Path(value="topic",encoded=true) topic:String) :Observable<List<User>>
我的死刑是:
fun getAllUsers(topic: String, onSuccess: Consumer<List<User>>, onFail:Consumer<Throwable>){
val api = NetworkLayer.getUserApi()
api.getAllUserFor(topic)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(onSuccess,onFail)
}
可以正常工作,除非没有该主题的用户,因为在没有用户的情况下,服务器将响应代码204,该代码作为异常收到.
Works fine except when there is no users for the topic, because when there is no users server respond with code 204 which received as an exception.
我正在使用ScalarsConverterFactory& GsonConverterFactory以使用Retrofit2解析Json响应.
I'm using ScalarsConverterFactory & GsonConverterFactory to parse the Json response with Retrofit2.
讨论了类似的问题此处,但是他们的服务器仅响应没有任何内容的http代码!在我的情况下,如果有一个或多个用户,则服务器将以Json正文的形式返回用户列表.在没有用户的情况下使用204进行响应,因此我需要处理这两种情况以及其他常见的http错误.
similar issue discussed here but their server responds only with http code without any content! In my case server will return a user list as a Json body when there is one or more users & response with 204 when there is no users, So I need to handle both cases along with other usual http errors.
推荐答案
标准方法是将响应包装在带有adapter-rxjava2依赖项的Result
中.
Standard way is wrapping the response in a Result
that comes with adapter-rxjava2 dependency.
@GET("/user/{topic}")
fun getAllUserFor(@Path(value="topic",encoded=true) topic:String) :Observable<Result<List<User>>>
这样,错误也会传递到onNext,您可以执行以下操作:
this way errors too are delivered to your onNext and you can do something like this:
api.getAllUserFor(topic)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe{ result ->
if(result.isError)
//Network Error
result.response()?.also {
if(result.isSuccessful)
//Success
else{
//api error
}
}
}
更干净,更简洁
通过以下方式检查状态
result.response?.code()
欢呼!
这篇关于Retrofit2使用RxJava的Observable概念处理HTTP 204(无内容响应)情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!