I am not able to get success response status code from response like 200,201.. etc. As we can easily get error codes from RetrofitError
class like error.isNetworkError()
and error.getResponse().getStatus()
. Is there any workaround for getting status codes?
To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error. Copied!
HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: Informational responses ( 100 – 199 ) Successful responses ( 200 – 299 )
HTTP response status codes (or simply status codes) are three-digit codes issued by a server in response to a browser-side request from a client. These status codes serve as a means of quick and concise communication on how the server worked on and responded to the client's request.
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 } }
You can get the status code in success()
just like you do it in failure()
@Override public void success(Object object, Response response) { response.getStatus() // returns status code integer }
Since you have a Response
object in success callback as response.getStatus()
EDIT
I assume you are using okhttp with retrofit.
okhttp has a powerful tool called Interceptor
You can catch the response before retrofits Callback and get status code from the response:
OkHttpClient client = new OkHttpClient(); client.interceptors().add(new Interceptor(){ @Override public Response intercept(Chain chain) throws IOException{ Request request = chain.request(); Response response = chain.proceed(request); response.code()//status code return response; }); // then add it to you Restclient like this: restAdapter = new RestAdapter.Builder() .setEndpoint(URL_SERVER_ROOT) .setClient(new OkClient(client)) //plus your configurations .build();
To learn more about interceptors visit here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With