0

我想通过apiuidcookie apitoken。但我只得到服务器上的第一个。这是我初始化 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);
        }
    }
4

1 回答 1

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 列表:https://www.rfc-editor.org/rfc/rfc2109#section-4.3.4,由分号或逗号分隔。但是,在 Android 的实现中,它们返回以分号分隔的。RFC2109Spec 对象希望它们用逗号分隔。因此,如果特定域有多个 cookie,则此代码将中断,并且仅传输列表中的第一个 cookie。

于 2016-01-12T11:54:24.310 回答