Search code examples
androidhttpconnection

How to go for refresh token automatically when access token expired and get 401 using HttpURLConnection in android?


I have post request like below, Cant we make it automatic like Retrofit 2.0 interceptor if access token expires get refresh token and service call continues? without interruption?

URL url = new URL(myurl + "?access_token=" + access_token);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(100000000 /* milliseconds */);
conn.setConnectTimeout(150000000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("charset", "utf-8");
conn.setDoInput(true);
conn.connect();

Is there any method to do this automatically when we get 401 response code ?


Solution

  • As far as i know, No way is provided for this in any framework as this is purely requirement based. You will have to post SERIAL calls as stated below :

    1. Post Main Call with Access Token; Iff successful than Stop Else go to Step2
    2. Post Call for New Access Token with Refresh Token, If Successful Update access token and again Post Main call like step 1 with updated Access token.
    3. Same way if your refresh token can expire, than handle that in same SERIAL Way.

    Hope it helps a bit.