retrofit & okhttpclient intercept 401 response

10,644

I usually use inteceptors for requests only, and to handle errors set an error handler on the rest adapter builder, see example below:

Note: cause.getResponse() may return null

   yourRestAdapterBuilder.setErrorHandler(new ErrorHandler() {
                        @Override
                        public Throwable handleError(RetrofitError cause) {
                            switch (cause.getResponse().getStatus()) {
                                case 401:
                                    mLoginToken.delete();
                                    Toast.makeText(mApplication.getApplicationContext(), R.string.session_error, Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(mApplication.getApplicationContext(), LoginActivity.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                    mApplication.startActivity(intent);
                                default:
                                    // suppress or handle other errors
                                    break;
                            }
                        }
                    })
Share:
10,644
Boldijar Paul
Author by

Boldijar Paul

E-Mail: [email protected]

Updated on June 12, 2022

Comments

  • Boldijar Paul
    Boldijar Paul about 2 years

    I'm trying to see whenever I get a response from my API with code 401. But when I do, i get an IOException

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (response.code() == 401) {
            mLoginToken.delete();
            Toast.makeText(mApplication.getApplicationContext(), R.string.session_error, Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(mApplication.getApplicationContext(), LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            mApplication.startActivity(intent);
        }
        return response;
    }
    

    I will get the error java.io.IOException: unexpected end of stream on Connection{ proxy=DIRECT@ hostAddress= cipherSuite=none protocol=http/1.1} (recycle count=0)

    At the line

            Response response = chain.proceed(request);
    

    How should I get the responses with 401 (unauthorized code) in order to handle this?