Android:在进行HTTP调用时使用cookie保持服务器会话

Arc*_*pgc 6 php cookies session android http

服务器端会话存储在数据库中并使用cookie进行维护.因此,每个客户端都必须提供与数据库中的会话匹配的有效cookie.

在Android端:

DefaultHttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = client.execute(httppost);
Run Code Online (Sandbox Code Playgroud)

如果我使用相同的客户端进行所有服务器调用,则客户端会处理这些cookie.

但问题是,当客户端被破坏时,由于设备需要内存,cookie将丢失,任何后续服务器调用都不起作用.

有没有办法让HttpClient持久性?或者在android端维护cookie的常用方法是什么.

SBe*_*413 7

这样做的"正确"方法是实现CookieHandler:http: //developer.android.com/reference/java/net/CookieHandler.html

执行此操作的最基本方法是扩展Application并将其放在应用程序onCreate()中:

CookieHandler.setDefault(new CookieManager());
Run Code Online (Sandbox Code Playgroud)

请注意: 这只会实现DEFAULT CookieManger.默认的CookieManger将在您的应用程序的特定会话期间管理所有HTTP请求的cookie.但是,它没有任何方法可以在应用程序的后续使用中持久存储cookie.

为此,您需要通过实现CookieStore编写自己的cookie管理器:http: //developer.android.com/reference/java/net/CookieStore.html

以下是我在目前位于Google Play商店的应用中使用的CookieStore实施示例:

package com.touchvision.util;

import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import com.touchvision.Config;

/*
 * This is a custom cookie storage for the application. This
 * will store all the cookies to the shared preferences so that it persists
 * across application restarts.
 */
public class TvCookieStore implements CookieStore {

    private static final String LOGTAG = "TV-TvCookieStore";

    /*
     * The memory storage of the cookies
     */
    private Map<String, Map<String,String>> mapCookies = new HashMap<String, Map<String,String>>();
    /*
     * The instance of the shared preferences
     */
    private final SharedPreferences sharedPrefs;

    /*
     * @see java.net.CookieStore#add(java.net.URI, java.net.HttpCookie)
     */
    public void add(URI uri, HttpCookie cookie) {

        String domain = cookie.getDomain();     

        // Log.i(LOGTAG, "adding ( " + domain +", " + cookie.toString() );

        Map<String,String> cookies = mapCookies.get(domain);
        if (cookies == null) {
            cookies = new HashMap<String, String>(); 
            mapCookies.put(domain, cookies);
        }
        cookies.put(cookie.getName(), cookie.getValue());

        if (cookie.getName().startsWith("SPRING_SECURITY") && !cookie.getValue().equals("")){
           //  Log.i(LOGTAG, "Saving rememberMeCookie = " + cookie.getValue() );            
            // Update in Shared Preferences
            Editor e = sharedPrefs.edit();       
            e.putString(Config.PREF_SPRING_SECURITY_COOKIE, cookie.toString());       
            e.commit(); // save changes 
        }

    }

   /*
    * Constructor
    * 
    * @param  ctxContext the context of the Activity
    */
    public TvCookieStore(Context ctxContext) {

        // Log.i(LOGTAG, "constructor()");

        sharedPrefs = ctxContext.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
    }

    /*
     * @see java.net.CookieStore#get(java.net.URI)
     */
    public List<HttpCookie> get(URI uri) {

        List<HttpCookie> cookieList = new ArrayList<HttpCookie>();

        String domain = uri.getHost(); 

        // Log.i(LOGTAG, "getting ( " + domain +" )" );

        Map<String,String> cookies = mapCookies.get(domain);
        if (cookies == null) {
               cookies = new HashMap<String, String>(); 
               mapCookies.put(domain, cookies);
        }  

        for (Map.Entry<String, String> entry : cookies.entrySet()) {
            cookieList.add(new HttpCookie(entry.getKey(), entry.getValue()));
            // Log.i(LOGTAG, "returning cookie: " + entry.getKey() + "="+ entry.getValue());
        }
        return cookieList; 

    }

    /*
     * @see java.net.CookieStore#removeAll()
     */
    public boolean removeAll() {

        // Log.i(LOGTAG, "removeAll()" );

        mapCookies.clear();
        return true;

    }        

    /*
     * @see java.net.CookieStore#getCookies()
     */
    public List<HttpCookie> getCookies() {

        Log.i(LOGTAG, "getCookies()" );

        Set<String> mapKeys = mapCookies.keySet();

        List<HttpCookie> result = new ArrayList<HttpCookie>();
        for (String key : mapKeys) {
            Map<String,String> cookies =    mapCookies.get(key);
            for (Map.Entry<String, String> entry : cookies.entrySet()) {
                result.add(new HttpCookie(entry.getKey(), entry.getValue()));
                Log.i(LOGTAG, "returning cookie: " + entry.getKey() + "="+ entry.getValue());
            }             
        }

        return result;

    }

    /*
     * @see java.net.CookieStore#getURIs()
     */
    public List<URI> getURIs() {

        Log.i(LOGTAG, "getURIs()" );

        Set<String> keys = mapCookies.keySet();
        List<URI> uris = new ArrayList<URI>(keys.size());
        for (String key : keys){
            URI uri = null;
            try {
                uri = new URI(key);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            uris.add(uri);
        }
        return uris;

    }

    /*
     * @see java.net.CookieStore#remove(java.net.URI, java.net.HttpCookie)
     */
    public boolean remove(URI uri, HttpCookie cookie) {

        String domain = cookie.getDomain();     

        Log.i(LOGTAG, "remove( " + domain +", " + cookie.toString() );

        Map<String,String> lstCookies = mapCookies.get(domain);

        if (lstCookies == null)
            return false;

        return lstCookies.remove(cookie.getName()) != null;

    }

}
Run Code Online (Sandbox Code Playgroud)

上面的自定义CookieStore使用SharedPreferences来保存cookie.您实现上面的类与您在应用程序类中实现默认CookieManager的方式类似,但该行看起来像这样:

CookieHandler.setDefault( new CookieManager( new TvCookieStore(this), CookiePolicy.ACCEPT_ALL));
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,唯一真正关心持久化的Cookie是Spring Security Cookie(我们在服务器端使用Spring Framework).您的代码显然会有所不同,以满足您的特定需求.

另一个快速说明:我无数次尝试做你正在做的事情,并在我的http客户端类中处理cookie的持久性.这只不过是头痛.给这个策略一个机会.