How to get https status code in Retrofit RxJava Android?
You should wrap your ResponseData inside Response as
Observable<Response<ResponseData>> observable = apiService.getData();
Then inside onNext
@Override
public void onNext(Resposne<ResponseData> response) {
int statusCode = response.code();
}
and for error
@Override
public void onError(Throwable e) {
((HttpException) e).code();
}
Get response status code using Retrofit 2.0 and RxJava
Instead of declaring the API call like you did:
Observable<MyResponseObject> apiCall(@Body body);
You can also declare it like this:
Observable<Response<MyResponseObject>> apiCall(@Body body);
You will then have a Subscriber like the following:
new Subscriber<Response<StartupResponse>>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {
Timber.e(e, "onError: %", e.toString());
// network errors, e. g. UnknownHostException, will end up here
}
@Override
public void onNext(Response<StartupResponse> startupResponseResponse) {
Timber.d("onNext: %s", startupResponseResponse.code());
// HTTP errors, e. g. 404, will end up here!
}
}
So, server responses with an error code will also be delivered to onNext
and you can get the code by calling reponse.code()
.
http://square.github.io/retrofit/2.x/retrofit/retrofit/Response.html
EDIT: OK, I finally got around to looking into what e-nouri said in their comment, namely that only 2xx codes will to to onNext
. Turns out we are both right:
If the call is declared like this:
Observable<Response<MyResponseObject>> apiCall(@Body body);
or even this
Observable<Response<ResponseBody>> apiCall(@Body body);
all responses will end up in onNext
, regardless of their error code. This is possible because everything is wrapped in a Response
object by Retrofit.
If, on the other hand, the call is declared like this:
Observable<MyResponseObject> apiCall(@Body body);
or this
Observable<ResponseBody> apiCall(@Body body);
indeed only the 2xx responses will go to onNext
. Everything else will be wrapped in an HttpException
and sent to onError
. Which also makes sense, because without the Response
wrapper, what should be emitted to onNext
? Given that the request was not successful the only sensible thing to emit would be null
...
Retrofit response codes with RxJava2
When Response from Server is code < 200 || code >= 300
in those cases onError()
will be invoked. and other cases onNext()
will invoke.
Also, If your code from onNext()
throws any exception, that will be catch in onError()
Retrofit/RxJava - get http response code
Just use casting??
mcityService.signOut(signOutRequest)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(resp ->
{
busyIndicator.dismiss();
finish();
}, throwable ->
{
Log.d(tag, throwable.toString());
Log.d(code, ((HttpException)throwable).code());
busyIndicator.dismiss();
Toast.makeText(this,throwable.getMessage(),Toast.LENGTH_LONG).show();
finish();
});
How to use Retrofit with RxJava when the status code is 400 to get me the error message?
This can be done using Rx and here is how:
mSubscription.add(mDataManager.login(username, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<User>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (NetworkUtil.isHttpStatusCode(e, 400) || NetworkUtil.isHttpStatusCode(e, 400)) {
ResponseBody body = ((HttpException) e).response().errorBody();
try {
getMvpView().onError(body.string());
} catch (IOException e1) {
Timber.e(e1.getMessage());
} finally {
if (body != null) {
body.close();
}
}
}
}
@Override
public void onNext(User user) {
//TODO Handle onNext
}
}));
}
NetworkUtil
public class NetworkUtil {
/**
* Returns true if the Throwable is an instance of RetrofitError with an
* http status code equals to the given one.
*/
public static boolean isHttpStatusCode(Throwable throwable, int statusCode) {
return throwable instanceof HttpException
&& ((HttpException) throwable).code() == statusCode;
}
}
Android Retrofit + Rxjava: How to get response on non200 code?
So technically, I can get response 2xx. The problem was that server response body in response code 205 that suppose to be null (https://www.rfc-editor.org/rfc/rfc7231#section-6.3.6). So after set body null on server, android side works fine.
retrofit2 rxjava 2 - how can access to body of response when have error
I find solution
in retrofit onSuccess methode when response code is 200, you should get response from body object.
but when isn't 200, you should get response from errorBody;
new Gson().fromJson(serverResultResponse.errorBody().string(), ServerResult.class);
Related Topics
Display a Part of the Webpage on the Webview Android
How to Use Mkfifo Using Android's Ndk
Cli on Dalvikvm Fails on Jni Lib
Android Draw Route on a Mapview with Twoo Poi-S
Android Material Chip Component Crashing App. Unable to Inflate Xml
Java.Lang.Noclassdeffounderror: Failed Resolution Of: Landroid/Support/V4/Os/Buildcompat
Android - Navigation View Item Menu Background Color
Android - Nestedscrollview Which Contains Expandablelistview Doesn't Scroll When Expanded
Transfer Data from One Activity to Another Activity Using Intents
How to Update UI from Asynctask
@Android Display /Res/Viewable in Webview
Outofmemory Exception When Loading Bitmap from External Storage