96

我有一个服务器,它向我的 android 应用程序发送一个会话 cookie,用于经过身份验证的通信。我正在尝试使用指向同一服务器的 URL 加载 WebView,并且我正在尝试传入会话 cookie 以进行身份​​验证。我观察到它间歇性地工作,但我不知道为什么。我使用相同的会话 cookie 在我的服务器上进行其他调用,并且这些调用永远不会失败。我仅在尝试在 WebView 中加载 URL 时观察到此问题,并且并非每次都发生。非常令人沮丧。

下面是我用来执行此操作的代码。任何帮助将不胜感激。

String myUrl = "http://example.com/"; 
CookieSyncManager.createInstance(this); 
CookieManager cookieManager = CookieManager.getInstance(); 
Cookie sessionCookie =  getCookie(); 
if(sessionCookie != null){ 
    String cookieString = sessionCookie.getName() +"="+sessionCookie.getValue()+"; domain="+sessionCookie.getDomain(); 
    cookieManager.setCookie(myUrl, cookieString); 
    CookieSyncManager.getInstance().sync(); 
} 

WebView webView = (WebView) findViewById(R.id.webview); 
webView.getSettings().setBuiltInZoomControls(true); 
webView.getSettings().setJavaScriptEnabled(true); 
webView.setWebViewClient(new MyWebViewClient()); 
webView.loadUrl(myUrl);
4

16 回答 16

57

感谢justingrammens!这对我有用,我设法在我的 DefaultHttpClient 请求和 WebView 活动中共享 cookie:

//------- Native request activity
private DefaultHttpClient httpClient;
public static Cookie cookie = null;

//After Login
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
for (int i = 0; i < cookies.size(); i++) {
    cookie = cookies.get(i);
}

//------- Web Browser activity
Cookie sessionCookie = myapp.cookie;
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
if (sessionCookie != null) {
    cookieManager.removeSessionCookie();
    String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
    cookieManager.setCookie(myapp.domain, cookieString);
    CookieSyncManager.getInstance().sync();
}   
于 2010-02-27T23:13:31.440 回答
21

感谢 Android 毁了我的星期天。. . 继承人是什么修复了我的应用程序(在你初始化你的 webview 之后)

if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {

  CookieManager cookieManager = CookieManager.getInstance();

  cookieManager.setAcceptThirdPartyCookies( webView, true );

}

我应该说上面的答案可能会起作用,但在我的情况下,Android 进入 v5+ 的那一刻,我的 android webview javascript 'apps' 就死了。

于 2016-01-17T07:33:39.507 回答
14

解决方案:Webview CookieSyncManager

CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie("http://xx.example.com","mid="+MySession.GetSession().sessionId+" ; Domain=.example.com");
cookieSyncManager.sync();

String cookie = cookieManager.getCookie("http://xx.example.com");

Log.d(LOGTAG, "cookie ------>"+cookie);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TuWebViewClient());
mWebView.loadUrl("http://xx.example.com");
于 2012-06-27T20:32:53.703 回答
6

解决方案是给 Android 足够的时间来处理 cookie。您可以在此处找到更多信息:http: //code.walletapp.net/post/46414301269/passing-cookie-to-webview

于 2011-04-18T13:09:12.053 回答
3

我会将该会话 cookie 保存为首选项,并用它强制重新填充 cookie 管理器。听起来会话cookie无法在活动重启中幸存

于 2009-10-31T00:03:46.023 回答
3

我花了 3 个小时的大部分时间来处理一个非常相似的问题。就我而言,我有很多调用,我使用 a 对 Web 服务进行了调用,DefaulHttpClient然后我想在我的WebView.

我不知道这是否能解决你的问题,因为我不知道你的getCookie()方法是做什么的,但就我而言,我实际上不得不打电话。

cookieManager.removeSessionCookie();

首先删除会话cookie,然后重新添加它。我发现当我尝试设置JSESSIONIDcookie 而不先删除它时,我想要设置的值没有被保存。不确定这是否会帮助您解决特定问题,但我想我会分享我的发现。

于 2010-01-23T03:13:03.793 回答
3

经过一段时间的研究,我收集了一些让我得到这个解决方案的部分。一旦 CookieSyncManager 被弃用,这可能是当今在 Kotlin 中为 web 视图设置特定 cookie 的最佳方式,您不需要其他任何东西。

private fun setCookie(){
    val webView = WebView(this) // this = context
    val cookieManager = CookieManager.getInstance()
    cookieManager.acceptCookie()

    val domain = "https://www.yourdomain.com/"

    webView.webViewClient = WebViewClient()
    webView.settings.javaScriptEnabled = true

    cookieManager.setCookie(domain,"$cookieKey=$cookieValue")
    cookieManager.setAcceptThirdPartyCookies(webView, true)

    webView.loadUrl(domain)
}
于 2019-10-31T14:42:35.693 回答
2

我从我的经验中发现了几条评论(至少对于 API >= 21),这让我很头疼:

  1. httphttps网址是不同的。设置 cookiehttp://www.example.com与设置 cookie 不同https://www.example.com
  2. 网址末尾的斜线也可以有所作为。在我的情况下https://www.example.com/工作但https://www.example.com不工作。
  3. CookieManager.getInstance().setCookie正在执行异步操作。因此,如果您在设置 url 后立即加载它,则不能保证 cookie 已经被写入。为了防止意外和不稳定的行为,请使用 CookieManager#setCookie(String url, String value, ValueCallback callback) ( link ) 并在调用回调后开始加载 url。

我希望我的两分钱可以节省一些人的时间,这样你就不必像我一样面对同样的问题。

于 2018-10-24T12:52:35.730 回答
1

我有一种与这里的其他人不同的方法,它是一种无需处理 CookieSyncManager 就可以保证工作的方法(您受制于诸如“请注意,即使 sync() 异步发生”之类的语义)。

本质上,我们浏览到正确的域,然后我们从页面上下文中执行 javascript 来为该域设置 cookie(与页面本身相同的方式)。该方法的两个缺点是,由于您必须发出额外的 http 请求,可能会引入额外的往返时间;如果您的网站没有空白页面,它可能会在将您带到正确位置之前先显示您首先加载的任何 URL。

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.cookie.Cookie;
import android.annotation.SuppressLint;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewFragment {
    private static final String BLANK_PAGE = "/blank.html"

    private CookieSyncManager mSyncManager;
    private CookieManager mCookieManager;

    private String mTargetUrl;
    private boolean mInitializedCookies;
    private List<Cookie> mAllCookies;

    public WebViewFragment(Context ctx) {
        // We are still required to create an instance of Cookie/SyncManager.
        mSyncManager = CookieSyncManager.createInstance(ctx);
        mCookieManager = CookieManager.getInstance();
    }

    @SuppressLint("SetJavaScriptEnabled") public void loadWebView(
                String url, List<Cookie> cookies, String domain) {
        final WebView webView = ...

        webView.setWebViewClient(new CookeWebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);

        mInitializedCookies = false;
        mTargetUrl = url;
        mAllCookies = cookies;
        // This is where the hack starts.
        // Instead of loading the url, we load a blank page.
        webView.loadUrl("http://" + domain + BLANK_PAGE);
    }

    public static String buildCookieString(final Cookie cookie) {
        // You may want to add the secure flag for https:
        // + "; secure"
        // In case you wish to convert session cookies to have an expiration:
        // + "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
        // Note that you cannot set the HttpOnly flag as we are using
        // javascript to set the cookies.
        return cookie.getName() + "=" + cookie.getValue()
                    + "; path=" + cookie.getPath()
                    + "; domain=" + cookie.getDomain()
    };

    public synchronized String generateCookieJavascript() {
        StringBuilder javascriptCode = new StringBuilder();
        javascriptCode.append("javascript:(function(){");
        for (final Cookie cookie : mAllCookies) {
            String cookieString = buildCookieString(cookie);
            javascriptCode.append("document.cookie=\"");
            javascriptCode.append(
                     StringEscapeUtils.escapeJavascriptString(cookieString));
            javascriptCode.append("\";");
        }
        // We use javascript to load the next url because we do not
        // receive an onPageFinished event when this code finishes.
        javascriptCode.append("document.location=\"");
        javascriptCode.append(
                StringEscapeUtils.escapeJavascriptString(mTargetUrl));
        javascriptCode.append("\";})();");
        return javascriptCode.toString();
    }

    private class CookieWebViewClient extends WebViewClient {
        @Override public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!mInitializedCookies) {
                mInitializedCookies = true;
                // Run our javascript code now that the temp page is loaded.
                view.loadUrl(generateCookieJavascript());
                return;
            }
        }
    }
}

如果您信任 cookie 来自的域,您可能可以在没有 apache commons 的情况下逃脱,但您必须了解,如果您不小心,这可能会带来 XSS 风险。

于 2013-04-02T19:02:44.390 回答
1

也遇到过这个。这就是我所做的。

在我的 LoginActivity 上,在我的 AsyncTask 中,我有以下内容:

CookieStoreHelper.cookieStore = new BasicCookieStore();
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, CookieStoreHelper.cookieStore);

HttpResponse postResponse = client.execute(httpPost,localContext);
CookieStoreHelper.sessionCookie = CookieStoreHelper.cookieStore.getCookies();

//WHERE CookieStoreHelper.sessionCookie 是另一个类,其中包含定义为 List cookies 的变量 sessionCookie;和 cookieStore 定义为 BasicCookieStore cookieStore;

然后在我的 WebView 所在的 Fragment 上,我有以下内容:

//DECLARE LIST OF COOKIE
List<Cookie> sessionCookie;

在我的方法中或在您设置 WebViewClient() 之前

WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

sessionCookie = CookieStoreHelper.cookieStore.getCookies();
CookieSyncManager.createInstance(webView.getContext());
CookieSyncManager.getInstance().startSync();
CookieManager cookieManager = CookieManager.getInstance();
CookieManager.getInstance().setAcceptCookie(true);
if (sessionCookie != null) {
   for(Cookie c:  sessionCookie){
      cookieManager.setCookie(CookieStoreHelper.DOMAIN, c.getName() + "=" + c.getValue());
   }
   CookieSyncManager.getInstance().sync();

 }

 webView.setWebViewClient(new WebViewClient() {
    //AND SO ON, YOUR CODE
 }

快速提示:在 firefox 上安装 firebug 或在 chrome 上使用开发者控制台并首先测试您的网页,捕获 Cookie 并检查域,以便将其存储在某个地方,并确保您正确设置了正确的域。

编辑:将 CookieStoreHelper.cookies 编辑为 CookieStoreHelper.sessionCookie

于 2014-11-07T07:57:20.543 回答
1

我用 onCreate 中的这一行神奇地解决了我所有的 cookie 问题:

CookieHandler.setDefault(new CookieManager());

编辑:它今天停止工作。:( 什么废话,安卓。

于 2013-10-18T19:18:50.397 回答
1

这是一段工作代码。

    private void setCookie(DefaultHttpClient httpClient, String url) {
    List<Cookie> cookies = httpClient.getCookieStore().getCookies();
    if (cookies != null) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);

        for (int i = 0; i < cookies.size(); i++) {
            Cookie cookie = cookies.get(i);
            String cookieString = cookie.getName() + "=" + cookie.getValue();
            cookieManager.setCookie(url, cookieString);
        }
        CookieSyncManager.getInstance().sync();
    }
}

这里的 httpclient 是您在 HttpGet/HttpPost 请求中使用的 DefaultHttpClient 对象。还要确保的一件事是 cookie 名称和值,应该给出

String cookieString = cookie.getName() + "=" + cookie.getValue();

setCookie 将为给定的 URL 设置 cookie。

于 2013-08-06T10:30:10.107 回答
1

我的工作代码

public View onCreateView(...){
    mWebView = (WebView) view.findViewById(R.id.webview);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

        ...
        ...
        ...

    CookieSyncManager.createInstance(mWebView.getContext());
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    //cookieManager.removeSessionCookie(); // remove
    cookieManager.removeAllCookie(); //remove
    // Recommended "hack" with a delay between the removal and the installation of "Cookies"
    SystemClock.sleep(1000);

    cookieManager.setCookie("https://my.app.site.com/", "cookiename=" + value + "; path=/registration" + "; secure"); // ;
    CookieSyncManager.getInstance().sync();

    mWebView.loadUrl(sp.getString("url", "") + end_url);

    return view;
}

要调试查询,“cookieManager.setCookie (....);” 建议你查看一下数据库webviewCookiesChromium.db的内容(存储在“/data/data/my.app.webview/database”)那里可以看到正确的设置。

禁用“cookieManager.removeSessionCookie();” 和/或“cookieManager.removeAllCookie();”

//cookieManager.removeSessionCookie();
// and/or
//cookieManager.removeAllCookie();"

将设置值与浏览器设置的值进行比较。调整之前安装 cookie 的请求,直到未安装“flags”浏览器将符合您的决定。我发现查询可以是“标志”:

// You may want to add the secure flag for https:
+ "; secure"
// In case you wish to convert session cookies to have an expiration:
+ "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
// These flags I found in the database:
+ "; path=/registration"
+ "; domain=my.app.site.com"
于 2015-08-24T18:39:59.447 回答
0

请注意,使用子域而不是通常的 URL 可能会更好。所以,设置.example.com而不是https://example.com/.

感谢 Jody Jacobus Geers 和其他人,我这样写:

if (savedInstanceState == null) {
    val cookieManager = CookieManager.getInstance()
    cookieManager.acceptCookie()
    val domain = ".example.com"
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        cookieManager.setCookie(domain, "token=$token") {
            view.webView.loadUrl(url)
        }
        cookieManager.setAcceptThirdPartyCookies(view.webView, true)
    } else {
        cookieManager.setCookie(domain, "token=$token")
        view.webView.loadUrl(url)
    }
} else {
    // Check whether we're recreating a previously destroyed instance.
    view.webView.restoreState(savedInstanceState)
}
于 2020-04-29T14:34:45.123 回答
0

我遇到了同样的问题,它将在所有 android 版本中解决这个问题

private void setCookie() {
    try {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.setCookie(Constant.BASE_URL, getCookie(), value -> {
                String cookie = cookieManager.getCookie(Constant.BASE_URL);
                CookieManager.getInstance().flush();
                CustomLog.d("cookie", "cookie ------>" + cookie);
                setupWebView();
            });
        } else {
            cookieManager.setCookie(webUrl, getCookie());
            new Handler().postDelayed(this::setupWebView, 700);
            CookieSyncManager.getInstance().sync();
        }

    } catch (Exception e) {
        CustomLog.e(e);
    }
}
于 2018-10-29T08:36:33.583 回答
-4

不要使用您的原始网址

代替:

cookieManager.setCookie(myUrl, cookieString); 

像这样使用它:

cookieManager.setCookie("your url host", cookieString); 
于 2015-05-12T04:54:01.307 回答