vt-dev0
vt-dev0

Reputation: 773

Persistent Cookie Storing with HTTPUrlConnection

I am currently working on an app that has the main purpose of letting a person log in and then displaying some information to that person.

I am using HttpUrlConnection to send and receive input from the website.

Since the app is mainly web-oriented, I need to make sure that a user can stay logged in even after closing the app, which means that I need to save Session Cookies somehow.

I have read about CookieManager and CookieStore, however, they are not fit for this because they only store cookies while app is open and they lose all information as soon as app is closed.

What is a good and safe way to store session cookies permanently on the device?

Upvotes: 2

Views: 80

Answers (2)

Yunus Karakaya
Yunus Karakaya

Reputation: 531

You can use SharedPreferences. Even if your app opens and closes, it can keep the data here. You can easily get it later. You can review here Sample code below for SharedPreferences.

SharedPreferences sp;
sp = getSharedPreferences("sampleName",MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("key", "value");
editor.commit();

There is another way to solve this problem. You can write files and read them when needed. The sample code is below for solution. And you can review here

public static void writeStringAsFile(final String fileContents, String fileName) {
    Context context = App.instance.getApplicationContext();
    try {
        FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
        out.write(fileContents);
        out.close();
    } catch (IOException e) {
        Logger.logError(TAG, e);
    }  
}
public static String readFileAsString (String fileName) {

    Context context = App.instance.getApplicationContext();
    StringBuilder stringBuilder = new StringBuilder();
    String line;
    BufferedReader in = null;

    try {
        in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
        while ((line = in.readLine()) != null) stringBuilder.append(line);

    } catch (FileNotFoundException e) {
        Logger.logError(TAG, e);
    } catch (IOException e) {
        Logger.logError(TAG, e);
    } 

    return stringBuilder.toString();
}

Upvotes: 2

Filip Sollár
Filip Sollár

Reputation: 91

You can save the cookies using SharedPreferences. It is the most used framework in android to store simply key:value data.

Upvotes: 1

Related Questions