代码之家  ›  专栏  ›  技术社区  ›  Vidar Vestnes

如何在Android中使用DefaultHttpClient创建持久cookie?

  •  3
  • Vidar Vestnes  · 技术社区  · 16 年前

    // this is a DefaultHttpClient
    List<Cookie> cookies = this.getCookieStore().getCookies();
    

    我的目标是将DefaultHttpClient与持久cookie一起使用。

    有经验的人能让我走上正轨吗?可能还有另一个我没有发现的最佳实践。。。

    2 回复  |  直到 16 年前
        1
  •  6
  •   BalusC    16 年前

    创建自己的 SerializableCookie implements Serializable 然后复制 Cookie

    public class SerializableCookie implements Serializable {
    
        private String name;
        private String path;
        private String domain;
        // ...
    
        public SerializableCookie(Cookie cookie) {
            this.name = cookie.getName();
            this.path = cookie.getPath();
            this.domain = cookie.getDomain();
            // ...
        }
    
        public String getName() {
            return name;
        }
    
        // ...
    
    }
    

    确保所有属性本身也是可序列化的。除了原语 String 例如类本身 实现序列化接口 所以你不用担心。

    曲奇 transient writeObject() readObject() 方法 accordingly

    public class SerializableCookie implements Serializable {
    
        private transient Cookie cookie;
    
        public SerializableCookie(Cookie cookie) {
            this.cookie = cookie;
        }
    
        public Cookie getCookie() {
            return cookie;
        }
    
        private void writeObject(ObjectOutputStream oos) throws IOException {
            oos.defaultWriteObject();
            oos.writeObject(cookie.getName());
            oos.writeObject(cookie.getPath());
            oos.writeObject(cookie.getDomain());
            // ...
        }
    
        private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
            ois.defaultReadObject();
            cookie = new Cookie();
            cookie.setName((String) ois.readObject());
            cookie.setPath((String) ois.readObject());
            cookie.setDomain((String) ois.readObject());
            // ...
        }
    
    }
    

    最后在 List

        2
  •  2
  •   loopj    15 年前

    Android异步Http库支持对SharedReference的自动持久cookie存储:

    http://loopj.com/android-async-http/

    或者,如果仍要使用DefaultHttpClient,可以提取并使用PersistentCookieStore.java和SerializableCookie.java类。

    推荐文章