Using CookieManager to Save Cookies on Android

Asked 2 years ago, Updated 2 years ago, 28 views

I made a post request from Android to the web server and
I'm trying to create an app that stores cookies.
(post parameters are not implemented)

If we didn't discard the activity, we were able to save and pass the cookie using the code below.
However, once you drop the app, the cookies are gone.

I've looked into various things, but I don't know the cause.
Do I have to save it in sharedPreferences and take it out every time?

I'm a beginner on Android, but I'd appreciate it if you could teach me.
Thank you for your cooperation.

package com.example.test;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class HttpResponsAsync extensions AsyncTask<Void, Void, String>{

    private TextView textView;
    static final String COOKIES_HEADER="Set-Cookie";
    static java.net.CookieManager msCookieManager=new java.net.CookieManager();

    private Context context = null;
    private ProgressDialog dialog = null;
    private String title;
    private String msg;

    /**
     * constructor
     */
    public HttpResponsAsync (Context context) {
        super();
        this.context=context;
    }

    @ Override
    protected void onPreExecute() {
        super.onPreExecute();
        // doInBackground preprocessing
    }

    @ Override
    Protected String doInBackground (Void...params) {
        String readSt = null;


        HttpURLConnection con=null;
        URL url = null;
        String urlSt="https://URL.com";

        try{
            // Creating URLs
            url = new URL(urlSt);
            // Creating HttpURLConnection Objects for Connections
            con=(HttpURLConnection) url.openConnection();
            if(msCookieManager.getCookieStore().getCookies().size()>0){
                // While joining the Cookies, use', 'or'; 'as needed. Most of the server are using';'
                con.setRequestProperty("Cookie",
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
            }

            // Configuring Request Methods
            con.setRequestMethod("POST");
            // Configuring Not Automatically Allow Redirects
            con.setInstanceFollowRedirects (false);
            // True if reading data from URL connection
            con.setDoInput(true);
            // True to write data to URL connection
            con.setDoOutput(true);

            // CONNECTION
            con.connect();
            Map<String, List<String>>headerFields=con.getHeaderFields();
            List<String>cookiesHeader=headerFields.get(COOKIES_HEADER);

            if(cookiesHeader!=null){
                for (String cookie: cookiesHeader) {
                    msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
                }
            }

            InputStream in=con.getInputStream();
            readSt = readInputStream(in);


        } catch(MalformedURLExceptione){
            e.printStackTrace();
        } catch(IOExceptione){
            e.printStackTrace();
        }

        return readSt;
    }

    public String readInputStream (InputStream in) flows IOException,
    UnsupportedEncodingException {
        StringBuffersb = new StringBuffer();
        String st="";

        BufferedReader br = new BufferedReader (new InputStreamReader(in, "UTF-8"));
        while((st=br.readLine())!=null){
            sb.append(st);
        }
        try { in.close();
        } catch(Exceptione){
            e.printStackTrace();
        }

        return sb.toString();
    }

    @ Override
    protected void onPostExecute(String result){
        super.onPostExecute(result);
        // doInBackground Postprocessing
        JSONArray jsonArray = null;
        try{
            // To retrieve an array
            jsonArray = new JSONObject(result).getJSONArray("data");
            int count = jsonArray.length();
            JSONObject[]bookObject=new JSONObject[count];
            for(inti=0;i<count;i++){
                bookObject[i] = jsonArray.getJSONObject(i);
                // For String type:
                String st = bookObject[i].getString("type");
            }
        } catch(JSONExceptione){
        }
    }

}

android java

2022-09-30 10:50

1 Answers

Persistent cookies require a little effort.
Depending on the Http Client used, such as OkHttp, the selection will change.
You can find many things when you search "android cookie persistent".


2022-09-30 10:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.