问题描述
我在应用程序中使用特定的身份验证机制.要登录,应用程序会将登录请求发送到特定的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 can automatically retry unauthenticated requests. When a response is 401 Not Authorized, an Authenticator is asked to supply credentials. Implementations should build a new request that includes the missing credentials. If no credentials are available, return null to skip the retry.
您可以在此处了解更多信息.
You can read more about library here.
这篇关于自动重试401并使用HttpClient 4.3发送特定请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!