问题
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