Automatically retry on 401 and send specific request with HttpClient 4.3

。_饼干妹妹 提交于 2019-12-11 06:59:37

问题


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.

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.

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?


回答1:


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

Handling authentication. 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.




回答2:


Apparently the easiest way appeared to write a Proxy class over HttpClient that captured "execute" method result and if Auth was required did a custom request and re-invoked original method with original parameters.



来源:https://stackoverflow.com/questions/24032353/automatically-retry-on-401-and-send-specific-request-with-httpclient-4-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!