Я использую перехватчик, чтобы обновить sh мой токен с истекшим сроком действия. После обновления я пытаюсь отправить исходный запрос с новым обновленным токеном. Но я не могу отправить запрос с новым токеном.
Если токен действителен. Приложение работает нормально. Но когда токен недействителен. Я думаю, что сетевой запрос во фрагменте опережает запрос токена refre sh ...
Пожалуйста, помогите мне ...
INTERCEPTOR
public class HttpInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
//Build new request
Request.Builder builder = request.newBuilder();
builder.header("Accept", "application/json"); //if necessary, say to consume JSON
String token = PrefUtils.getAppToken(HelloApplication.getContext()); //save token of this request for future
setAuthHeader(builder, token); //write current token to request
request = builder.build(); //overwrite old request
Response response = chain.proceed(request); //perform request, here original request will be executed
String body = response.peekBody(2048).string();
try {
APIStatus stat = new Gson().fromJson(body, APIStatus.class);
Log.e("ARUL intercept: ", stat.getMessage());
if (stat.getMessage().contains("Invalid Auth Token")) { //if unauthorized
synchronized (this) { //perform all 401 in sync blocks, to avoid multiply token updates
String currentToken = PrefUtils.getAppToken(HelloApplication.getContext()); //get currently stored token
if (currentToken != null && currentToken.equals(token)) { //compare current token with token that was stored before, if it was not updated - do update
int code = refreshToken() / 100; //refresh token
if (code != 2) { //if refresh token failed for some reason
if (code == 4) //only if response is 400, 500 might mean that token was not updated
logout(); //go to login screen
return response; //if token refresh failed - show error to user
}
}
if (PrefUtils.getAppToken(HelloApplication.getContext()) != null) { //retry requires new auth token,
setAuthHeader(builder, PrefUtils.getAppToken(HelloApplication.getContext())); //set auth token to updated
request = builder.build();
return chain.proceed(request); //repeat request with new token
}
}
}
} catch (IllegalStateException | JsonSyntaxException exception) {
Log.e("ARUL intercept: ", "GOT VALID REPSONSE!!! ");
}
return response;
}
private void setAuthHeader(Request.Builder builder, String token) {
if (token != null) //Add Auth token to each request if authorized
builder.header("auth_token", token);
}
private int refreshToken() {
//Refresh token, synchronously, save it, and return result code
//you might use retrofit here
int status = 2;
HelloApi mHelloApi = ServiceGenerator.provideHelloService();
HashMap<String, RequestBody> partMap = new HashMap<>();
String ID = PrefUtils.getUserID(HelloApplication.getContext());
partMap.put("user_id", Utils.createPartFromString(ID));
Call<APIStatus> register = mHelloApi.requestAccessToken(partMap);
APIStatus mAPI = register.execute().body();
PrefUtils.updateToken(HelloApplication.getContext(), mAPI.getToken());
return status;
}
private int logout() {
//logout your user
return 4;
}
}
ФРАГМЕНТ
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mFactory = InjectorUtils.provideHomeFactory(getActivity());
mViewModel = new ViewModelProvider(this, mFactory).get(HomeViewModel.class);
if (mUser != null) {
Log.e("User EMAIL > ", mUser.getEmail());
Log.e("User ID > ", mUser.getUserID() + " > > " + mUser.getTokenAuthentication());
fetchDashboard();
}
}
private void fetchDashboard() {
partMap.put("user_id", Utils.createPartFromString(mUser.getUserID()));
mViewModel.getSnickers(partMap).observe(getActivity(), apiResponse -> {
if (apiResponse != null) {
mProgress.hide();
mDiscoverRVAdapter.setItems(apiResponse.getEntityStickers());
mDiscoverRVAdapter.notifyDataSetChanged();
}
});
}
LOGCAT
2020-08-03 11:13:04.210 10708-10708/com.hello.helloapp E/User ID >: 70 > > %MoJCCdoVqrRipyYgFrCShBK#XX#jEhkebRWOUkUr#eRgOK
2020-08-03 11:13:04.231 10708-10734/com.hello.helloapp D/OkHttp: --> POST http://sandbox.hello.com/api/mapi/dashboard
2020-08-03 11:13:04.231 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: multipart/form-data; boundary=3676a142-4869-46e1-b525-a3bdc72fe4a5
2020-08-03 11:13:04.231 10708-10734/com.hello.helloapp D/OkHttp: Content-Length: 240
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: --3676a142-4869-46e1-b525-a3bdc72fe4a5
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: Content-Disposition: form-data; name="user_id"
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: Content-Transfer-Encoding: binary
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: multipart/form-data; charset=utf-8
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: Content-Length: 2
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: 70
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: --3676a142-4869-46e1-b525-a3bdc72fe4a5--
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: --> END POST (240-byte body)
2020-08-03 11:13:04.238 10708-10734/com.hello.helloapp E/<HEADER>: Token Added > %MoJCCdoVqrRipyYgFrCShBK#XX#jEhkebRWOUkUr#eRgOK
2020-08-03 11:13:04.258 10708-10732/com.hello.helloapp I/OpenGLRenderer: Initialized EGL, version 1.4
2020-08-03 11:13:04.258 10708-10732/com.hello.helloapp D/OpenGLRenderer: Swap behavior 1
2020-08-03 11:13:04.259 10708-10732/com.hello.helloapp E/EGL_adreno: CreateContext rcMajorVersion:3, minorVersion:0
2020-08-03 11:13:04.272 10708-10732/com.hello.helloapp D/EGL_adreno: eglCreateContext: 0xb70052a0: maj 3 min 0 rcv 3
2020-08-03 11:13:04.313 10708-10732/com.hello.helloapp E/EGL_adreno: tid 10732: eglSurfaceAttrib(1582): error 0x3009 (EGL_BAD_MATCH)
2020-08-03 11:13:04.313 10708-10732/com.hello.helloapp W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9aa589e0, error=EGL_BAD_MATCH
2020-08-03 11:13:04.685 10708-10734/com.hello.helloapp E/ARUL intercept:: Invalid Auth Token
2020-08-03 11:13:04.714 10708-10734/com.hello.helloapp E/Current Token: %MoJCCdoVqrRipyYgFrCShBK#XX#jEhkebRWOUkUr#eRgOK
2020-08-03 11:13:04.719 10708-10734/com.hello.helloapp E/userID: > >70
2020-08-03 11:13:04.722 10708-10734/com.hello.helloapp D/OkHttp: --> POST http://sandbox.hello.com/api/mapi/get_token
2020-08-03 11:13:04.722 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: multipart/form-data; boundary=810973ea-31be-4f2c-81c4-a7d57298d526
2020-08-03 11:13:04.722 10708-10734/com.hello.helloapp D/OkHttp: Content-Length: 240
2020-08-03 11:13:04.723 10708-10734/com.hello.helloapp D/OkHttp: --810973ea-31be-4f2c-81c4-a7d57298d526
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: Content-Disposition: form-data; name="user_id"
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: Content-Transfer-Encoding: binary
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: multipart/form-data; charset=utf-8
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: Content-Length: 2
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: 70
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: --810973ea-31be-4f2c-81c4-a7d57298d526--
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: --> END POST (240-byte body)
2020-08-03 11:13:05.140 10708-10734/com.hello.helloapp D/OkHttp: <-- 200 OK http://sandbox.hello.com/api/mapi/get_token (415ms)
2020-08-03 11:13:05.140 10708-10734/com.hello.helloapp D/OkHttp: Connection: Keep-Alive
2020-08-03 11:13:05.140 10708-10734/com.hello.helloapp D/OkHttp: X-Powered-By: PHP/7.2.29
2020-08-03 11:13:05.140 10708-10734/com.hello.helloapp D/OkHttp: Set-Cookie: ci_session=e06bfe493b4e0b656d5a2c5a7dfee86364307e78; expires=Mon, 03-Aug-2020 07:43:04 GMT; Max-Age=7200; path=/; HttpOnly
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Expires: Thu, 19 Nov 1981 08:52:00 GMT
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Cache-Control: no-store, no-cache, must-revalidate
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Pragma: no-cache
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: text/html; charset=UTF-8
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Vary: Accept-Encoding
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Date: Mon, 03 Aug 2020 05:43:04 GMT
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Server: LiteSpeed
2020-08-03 11:13:05.143 10708-10734/com.hello.helloapp D/OkHttp: {"message_code":1,"message":"Result found.","token_authentication":"UYCVHZkFKkMhqbR#tbZIOAboy%A#hvRVuecNC%mBjUBTk@H"}
2020-08-03 11:13:05.144 10708-10734/com.hello.helloapp D/OkHttp: <-- END HTTP (117-byte body)
2020-08-03 11:13:05.163 10708-10734/com.hello.helloapp D/OkHttp: <-- 200 OK http://sandbox.hello.com/api/mapi/dashboard (931ms)
2020-08-03 11:13:05.163 10708-10734/com.hello.helloapp D/OkHttp: Connection: Keep-Alive
2020-08-03 11:13:05.163 10708-10734/com.hello.helloapp D/OkHttp: X-Powered-By: PHP/7.2.29
2020-08-03 11:13:05.163 10708-10734/com.hello.helloapp D/OkHttp: Set-Cookie: ci_session=c7d4a52827268f0f33fe51594fb0c314a21129a6; expires=Mon, 03-Aug-2020 07:43:04 GMT; Max-Age=7200; path=/; HttpOnly
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Expires: Thu, 19 Nov 1981 08:52:00 GMT
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Cache-Control: no-store, no-cache, must-revalidate
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Pragma: no-cache
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: text/html; charset=UTF-8
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Vary: Accept-Encoding
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Date: Mon, 03 Aug 2020 05:43:04 GMT
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Server: LiteSpeed
2020-08-03 11:13:05.165 10708-10734/com.hello.helloapp D/OkHttp: {"message_code":404,"message":"Invalid Auth Token","response":"Invalid Auth Token"}
2020-08-03 11:13:05.165 10708-10734/com.hello.helloapp D/OkHttp: <-- END HTTP (83-byte body)
2020-08-03 11:13:05.171 10708-10708/com.hello.helloapp D/AndroidRuntime: Shutting down VM
ОБНОВЛЕНИЕ
Обновленный токен успешно сохранен в общих Prefs. Но при повторной попытке исходного запроса. он все еще использует старый токен? Как это исправить?