How to get Retrofit success response status codes
As per Retrofit 2.0.2, the call is now
@Override
public void onResponse(Call<YourModel> call, Response<YourModel> response) {
if (response.code() == 200) {
// Do awesome stuff
} else {
// Handle other response codes
}
}
Hope it helps someone :-)
EDIT: Many apps could also benefit from just checking for success (response code 200-300) in one clause, and then handling errors in other clauses, as 201 (Created) and 202 (Accepted) would probably lead to the same app logic as 200 in most cases.
@Override
public void onResponse(Call<YourModel> call, Response<YourModel> response) {
if (response.isSuccessful()) {
// Do awesome stuff
} else if (response.code() == 401) {
// Handle unauthorized
} else {
// Handle other responses
}
}
Android - get response status code using retrofit and coroutines
Your interface would look like this
suspend fun getArticles(): Response<Articles>
then you use like this
val response = service.getArticles()
response.code() //gives you response code
val articles = response.body
or easier solution is
if (response.isSuccessful){ // Successful is any code between the range [200..300)
val articles = response.body
}
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
...
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();
}
Retrofit 2.0: getting response code 200 but not getting the desired data
As per your log, API calls properly. It also responds. but the issue is API authentication is failed from your back end. Add log on your web service and check. From the application side, it is working fine. this is not an issue of Retrofit.
Update your onResponse() with below and run application. then test and let me know what message you get.
if(response.body()!=null){
LoginResponse loginResponse = response.body();
String content="";
if (response.body().getResponseCode()==200){
content+= loginResponse.getData().getAccessToken();
content+= loginResponse.getData().getDisplayName();
content+= loginResponse.getData().getEmail();
content+= loginResponse.getData().getId();
content+= loginResponse.getData().getUsername();
}else{
content+=loginResponse.getData().getMsg();
}
Log.d(TAG, "onResponse: login res"+content);
} else {
Toast.makeText(LoginActivity.this, "Invalid response from server", Toast.LENGTH_SHORT).show();
}
Below code in Data.java
@SerializedName("msg")
@Expose
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
how to handle 206 code with retrofit in android?
You can wrap your CompanyListRest
response inside Response
like below:
Observable<Response<CompanyListRest>>
Response
comes from retrofit2:
import retrofit2.Response;
So now you can check response code for 206 in onNext
method:
@Override
public void onNext(Resposne<CompanyListRest> response) {
int statusCode = response.code();
if(statusCode == 206){
//do something...
}
}
To call this function again you just simply call this function again).
I would recommend you to have a repository where you can control all your requests.
Retrofit Coroutine Status Code 205 Body Null
Retrofit skips the converter if the status code is 204 or 205.
You can try adding an OkHttp Interceptor which would convert the server's 205 code to 200 before Retrofit works on it.
Like this:
class BodyInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
if (response.code == 204 || response.code == 205) {
return response
.newBuilder()
.code(200)
.body(response.body)
.build()
} else {
return response
}
}
}
Related Topics
How to Update My Adt in Eclipse
Cannot Resolve Method Setlatesteventinfo
Could Not Find Method Android() for Arguments
How to Store SQLite Database Directly on Sdcard
Cmusphinx Pocketsphinx - Recognize All (Or Large Amount) of Words
How to Serialize My User Class for the Firebase Database and Fix This Error
Android Asynctask Testing with Android Test Framework
How to Show Shadow Around the Linearlayout in Android
How to Get Images Dynamically from Drawable Folder
How to Align Title at Center of Actionbar in Default Theme(Theme.Holo.Light)
How to Pair Bluetooth Device Programmatically Android
Add Custom Font for Complete Android Application
Android Mask Bitmap on Canvas Gen a Black Space
How Does One Check If a Table Exists in an Android SQLite Database
Custom Dialog on Android: How to Center Its Title
How to Resolve "Missing Pendingintent Mutability Flag" Lint Warning in Android API 30+
What Method Should I Use Now Since Firebaseinstanceid.Getinstance().Gettoken() Is Deprecated