【问题标题】:Only first cookie gets on server, several others cookies don't只有第一个 cookie 进入服务器,其他几个 cookie 没有
【发布时间】:2016-01-12 11:54:24
【问题描述】:

我想通过 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);
        }
    }

【问题讨论】:

    标签: android cookies android-webview android-cookiemanager


    【解决方案1】:

    阅读代码后:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-28
      • 2019-05-30
      • 2012-12-14
      • 2017-08-18
      • 2021-04-19
      • 2011-04-23
      • 2014-04-28
      • 1970-01-01
      相关资源
      最近更新 更多