【问题标题】:retrofit & okhttpclient intercept 401 response改造 & okhttpclient 拦截 401 响应
【发布时间】:2016-02-27 20:44:40
【问题描述】:

我正在尝试查看何时从我的 API 收到代码 401 的响应。 但是当我这样做时,我得到一个 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: Connection{ proxy=DIRECT@ hostAddress= cipherSuite=none protocol=http/1.1} (recycle count=0)

上的流意外结束

排队

        Response response = chain.proceed(request);

我应该如何获得带有 401(未经授权的代码)的响应以处理此问题?

【问题讨论】:

    标签: android retrofit okhttp


    【解决方案1】:

    我通常只将 inteceptors 用于请求,并在 rest 适配器构建器上设置错误处理程序来处理错误,请参见下面的示例:

    注意: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;
                                }
                            }
                        })
    

    【讨论】:

    • 是否还有其他默认的错误处理程序,如果我设置一个新的,将来会有一些问题吗?
    • 如果我没记错的话,设置另一个错误处理程序只会覆盖先前设置的错误处理程序,而且我不确定您希望错误处理有多复杂,您总是可以抽象 case将代码块转换为静态函数以保持代码的可读性
    • 感谢您分享此解决方案。我喜欢它;)
    【解决方案2】:
    val contentType = response.body?.contentType()
            val charset: Charset = contentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8
            val message= response.body?.source()?.readString(charset)
    

    它对我有用,而且效果很好

    【讨论】:

      猜你喜欢
      • 2016-05-02
      • 2023-04-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      相关资源
      最近更新 更多