Using Cookies across Activities when using HttpClient

后端 未结 6 1832
孤独总比滥情好
孤独总比滥情好 2020-12-04 15:43

I\'m trying a simple app to read in the HTML of a website, and tranform it to create an easily readable UI in Android (This is an exersize in learning android, not to make a

6条回答
  •  抹茶落季
    2020-12-04 16:29

    In my application server wants to use same session with same cookies... After few hours of "googling" and painful headache I just saved cookies to SharedPreference or just put in some object and set DefaultHttpClient with same cookies again ... onDestroy just remove SharedPreferences ... that's all:

    1. First copy SerializableCookie class to your package: SerializableCookie

    Look the following example:

    public class NodeServerTask extends AsyncTask {
    private DefaultHttpClient client;
    
    
    protected String doInBackground(Void... params) {
      HttpPost httpPost = new HttpPost(url);
        List urlParameters = new ArrayList();
        urlParameters.add(nameValuePair);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
            List cookies = loadSharedPreferencesCookie();
            if (cookies!=null){
                CookieStore cookieStore = new BasicCookieStore();
                for (int i=0; i

    // two methods to save and load cookies ...

     private void saveSharedPreferencesCookies(List cookies) {
        SerializableCookie[] serializableCookies = new SerializableCookie[cookies.size()];
        for (int i=0;i loadSharedPreferencesCookie() {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        byte[] bytes = preferences.getString("cookies", "{}").getBytes();
        if (bytes.length == 0 || bytes.length==2)
            return null;
        ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);
        Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.DEFAULT);
        ObjectInputStream in;
        List cookies = new ArrayList();
        SerializableCookie[] serializableCookies;
        try {
            in = new ObjectInputStream(base64InputStream);
            serializableCookies = (SerializableCookie[]) in.readObject();
            for (int i=0;i

    Google Luck

提交回复
热议问题