改造& okhttpclient拦截401响应

时间:2016-02-27 20:44:40

标签: android retrofit okhttp

我试图通过代码401从我的API获得响应。 但是当我这样做时,我得到一个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;
}

我会收到错误 java.io.IOException:连接上的意外流结束{proxy = DIRECT @ hostAddress = cipherSuite = none protocol = http / 1.1}(recycle count = 0)

        Response response = chain.proceed(request);

如何处理401(未经授权的代码)才能处理此问题?

2 个答案:

答案 0 :(得分:6)

我通常只将请求程序用于请求,并且处理错误会在其余适配器构建器上设置错误处理程序,请参阅下面的示例:

  

注意:cause.getResponse()可能会返回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;
                            }
                        }
                    })

答案 1 :(得分:0)

val contentType = response.body?.contentType()
        val charset: Charset = contentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8
        val message= response.body?.source()?.readString(charset)

它对我有用,而且方法很好