0

I want to pass apiuid and apitoken by cookie. But I'm getting only the first one on server. This is my code to initialize cookies:

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);
        }
    }
Mann
  • 560
  • 3
  • 13
tiny sunlight
  • 6,231
  • 3
  • 21
  • 42

1 Answers1

0

After reading Code:

 /**
 * 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);

I notice that one is 'Set-Cookie',and the other is 'Cookie'. So,I think I can add one by one.

Final code is below:

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);
    }
}

Below is something I am not really sure:

According to Mark(http://blog.winfieldpeterson.com/2013/01/17/cookies-in-hybrid-android-apps/):

Please Note: This code is severely broken! The Android CookieManager gives back a cookie list formatted according to RFC2109 section 4.3.4: https://www.rfc-editor.org/rfc/rfc2109#section-4.3.4, which is delimited either by semi-colon or comma. However, in Android’s implementation, they return semi-colon delimited. The RFC2109Spec object expects them to be delimited by comma. Therefore, if there are multiple cookies for a particular domain, this code will break, and only transfer the first cookie in the list.

Community
  • 1
  • 1
tiny sunlight
  • 6,231
  • 3
  • 21
  • 42