自动重试 401 并使用 HttpClient 4.3 发送特定请求 [英] Automatically retry on 401 and send specific request with HttpClient 4.3

查看:26
本文介绍了自动重试 401 并使用 HttpClient 4.3 发送特定请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中使用特定的身份验证机制.登录应用程序将登录请求发送到特定的 url/login/并获取存储在 cookie 中的会话令牌.

I use specific auth mechanism in the app. To login app sends login request to specific url /login/ and gets back session token that is stored in cookie.

任何时候令牌都可以被服务器失效,其他请求会导致401.我想让HttpClient自动检测401错误,重做/login/请求一次,自动重试原始请求.

At any time token can be invalidated by server and other requests will result in 401. I want HttpClient to detect 401 error automatically, redo /login/ request once and retry original request automatically.

我尝试在 HttpClients.custom().setRetryHandler 中设置 HttpRequestRetryHandler 但它似乎不能处理 401 错误.

I've tried setting HttpRequestRetryHandler in HttpClients.custom().setRetryHandler but it seems it does not handle 401 errors.

执行请求的功能的最佳方式是什么?

What would be the best way of doing requested functionality?

推荐答案

您可以使用 OkHttpClient 来满足您的需求.它完全实现了您想要的.

You can use OkHttpClient for your needs. It implement exactly you want.

处理身份验证.OkHttp 可以自动重试未经身份验证的请求.当响应是 401 Not Authorized 时,认证器被要求提供凭证.实现应该构建一个包含缺失凭据的新请求.如果没有可用凭据,则返回 null 以跳过重试.

您可以在此处阅读有关图书馆的更多信息.

You can read more about library here.

这篇关于自动重试 401 并使用 HttpClient 4.3 发送特定请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆