在Android Retrofit中处理未经身份验证响应的正确方法是什么

发布于 2025-01-30 23:03:51 字数 1214 浏览 2 评论 0 原文

每当我遇到服务器的401响应时,我都想将用户带到登录屏幕。

我目前正在处理401:

public abstract class BaseCallback<T> implements Callback<T> {

    private final Context context;

    public BaseCallback(Context context) {
        this.context = context;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.code() == 401) {
            // launch login activity using `this.context`
        } else {
            onSuccess(response.body());
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {

    }

    abstract void onSuccess(T response);

}

https://stackoverflow.com/a/49789543/6341943”

androidviewmodel androidviewmodel )每当我打个API电话时。

我发现的另一种方法是使用拦截器。

我觉得应该有一种更好的方法来处理此问题,但是我找不到比这更好的东西。

Google如何处理?我找不到任何这样的示例应用程序。我尝试了 ioshed ,但找不到这样的东西。

请指向正确的方向。

I want to take the user to the login screen whenever I encounter a 401 response from the server.

I am currently handling 401 like this:

public abstract class BaseCallback<T> implements Callback<T> {

    private final Context context;

    public BaseCallback(Context context) {
        this.context = context;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.code() == 401) {
            // launch login activity using `this.context`
        } else {
            onSuccess(response.body());
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {

    }

    abstract void onSuccess(T response);

}

Courtesy of https://stackoverflow.com/a/49789543/6341943

But this way, I have to pass context from my ViewModel(my ViewModel is inherited from AndroidViewModel) whenever I make an API call.

Another way I found was to use an interceptor.

I feel like there should be a better way to handle this but I couldn't find something better than this.

How does Google handle this? I couldn't find any such sample apps. I tried ioshed but couldn't find anything like this.

Please point me in the right direction.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文