Saving cookies between HTTP requests sent by Android applications

I am creating an Android application to provide website functionality on Android phones.

People need to be logged in and they remain logged in with cookies, which allows them to do something under their account. All login / authentication code has been done for the website, and now I am writing an Android application to do the same.

My question is: if the Android application sends an HTTP request to the PHP server and the server sets some cookies in return (to indicate that the user is logged in), will these cookies store all future HTTP requests to the server in the Android application?

Or do I need to develop a new authentication scheme for Android, for example, transfer a special token to the user login application and an application that provides this token during all future requests for user authentication?

+4
source share
3 answers

You must use CookieManager and CookieStore to save cookies.

CookieManager will store the cookies for each incoming HTTP response in the CookieStore and retrieve cookies for each outgoing HTTP request. Excluded HttpCookies must be removed from this store on their own.

You would use this with the HttpURLConnection class.

+3
source

After entering the application, you should save the token in SharedPrefrences . And you can use Http in each request later. Even when the application restarts, you have this token. SharedPredPrefrence is better for this.

+3
source

after logging in to SharedPreferences

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("userName", "Rock"); editor.putString("token", " token@123 "); 

get from SharedPreferences

 SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); String username = sharedPreferences.getString("userName", ""); String token = sharedPreferences.getString("token", ""); 
+1
source

Source: https://habr.com/ru/post/1437133/


All Articles