How to get Retrofit success response status codes

前端 未结 3 1606
谎友^
谎友^ 2020-11-27 17:51

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.i

3条回答
  •  失恋的感觉
    2020-11-27 18:15

    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.

提交回复
热议问题