只有第一个cookie进入服务器,其他几个cookie没有

时间:2016-01-12 11:54:24

标签: android cookies android-webview android-cookiemanager

我想通过Cookie传递apiuidapitoken。但我只在服务器上获得第一个。 这是我初始化cookie的代码:

public static void initCookie(String uid,String token,String domain,Context context){
        try{
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();
            cookieManager.removeAllCookie();
            cookieManager.setCookie(domain,"apiuid="+uid +";apitoken="+token);
            CookieSyncManager.getInstance().sync();
        }catch(Throwable e){
            LogUtils.e(e);
        }
    }

1 个答案:

答案 0 :(得分:0)

阅读代码后:

 /**
 * Sets a cookie for the given URL. Any existing cookie with the same host,
 * path and name will be replaced with the new cookie. The cookie being set
 * will be ignored if it is expired.
 *
 * @param url the URL for which the cookie is to be set
 * @param value the cookie as a string, using the format of the 'Set-Cookie'
 *              HTTP response header
 */
public abstract void setCookie(String url, String value);

/**
 * Gets the cookies for the given URL.
 *
 * @param url the URL for which the cookies are requested
 * @return value the cookies as a string, using the format of the 'Cookie'
 *               HTTP request header
 */
public abstract String getCookie(String url);

我注意到一个是'Set-Cookie',另一个是'Cookie'。 所以,我想我可以逐个添加。

最终代码如下:

public static void initCookie(String uid,String token,String domain,Context context){
    try{
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();
        cookieManager.removeAllCookie();
        cookieManager.setCookie(domain,"apiuid="+uid);
        cookieManager.setCookie(domain,"apitoken="+token);
        CookieSyncManager.getInstance().sync();
    }catch(Throwable e){
        LogUtils.e(e);
    }
}

以下是我不确定的事情:

根据马克(http://blog.winfieldpeterson.com/2013/01/17/cookies-in-hybrid-android-apps/):

  

请注意:此代码严重破坏! Android CookieManager提供了一个根据RFC2109第4.3.4节格式化的cookie列表:http://tools.ietf.org/html/rfc2109#section-4.3.4,用分号或逗号分隔 。但是,在Android的实现中,它们返回分号分隔。 RFC2109Spec对象期望它们以逗号分隔。因此,如果特定域有多个cookie,则此代码将中断,并仅传输列表中的第一个cookie。