【问题标题】:DefaultHttpClient post get session cookie and pass to WebView androidDefaultHttpClient post获取会话cookie并传递给WebView android
【发布时间】:2012-12-03 13:45:36
【问题描述】:

我在 SO 上找到了这个问题的一些答案,但我没有成功实施它们,所以希望有人可以检查我的代码并告诉我哪里出错了。

我已验证我的 cookie 是从 DefaultHttpClient 设置的,并且正在使用 Log.d 将其写出,正如您在下面的代码 sn-p 中所见。一切都在那里,只是没有为在此代码段底部调用的 WebView 设置。传递下来的 cookie 是我的 Asp.net mvc 项目中的会话 cookie。任何想法为什么当 WebView 访问该站点时它没有让我保持登录状态?不要让 facebook 措辞让你失望,我都在工作,这个 cookie 用于我自己的服务器,它传递一个会话 cookie 以让我登录到自己的网站(基于我的 facebook 资料)。

Cookie sessionCookie = FacebookLoginService.cookie;
Log.d("intialwebview",sessionCookie.toString());
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
if (sessionCookie != null) {
    cookieManager.removeSessionCookie();
    String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
    Log.d("intialwebview",cookieString);
    cookieManager.setCookie(FacebookLoginService.cookie.getDomain(), cookieString);
    CookieSyncManager.getInstance().sync();
}  
//end cookie section


int userId = prefs.getInt(C.USER_ID, 0);
    webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setUserAgentString(webView.getSettings().getUserAgentString() + "(Rambo)");
webView.getSettings().setJavaScriptEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 
webView.loadUrl(C.BaseUrl + "home/firstpage");

编辑:我还尝试在代码中创建 Web 视图:

WebView webView = new WebView(this);

同样的结果。 Cookie 未发送到 webview。

【问题讨论】:

    标签: android webview httpclient session-cookies


    【解决方案1】:

    最终通过使用 Asynctask 并在后台运行 sleep 进行排序。

    【讨论】:

    • 嗨克里斯托弗,我遇到了同样的问题。昨天它在 android 4.1.2 上运行良好。今天它不适用于 4.0.3。我遵循相同的程序。有什么帮助吗?
    【解决方案2】:

    你用过这条线——

    if (sessionCookie != null) {
      cookieManager.removeSessionCookie();
      }
    

    确保您每次都能收到新的 cookie。 好像你经历过同样的问题 正如我所面临的,请查看以下链接 -

    removeSessionCookie() issue of android, (code.google.com)

    它说removeSessionCookie()是在一个线程中实现的,所以无论何时

    调用;一个线程开始,在你的setCookie(url, cookieString); 被调用之后,

    它会删除您刚刚设置的新 cookie。 因此,对于某些设备,它运行良好,因为 removeSessionCookie() 已经执行,

    虽然,对于某些人来说,它会删除 cookie,但我们遇到了这个问题。

    我建议你删除这个removeSessionCookie();,因为你只设置了一个cookie,所以它不会与其他cookie冲突。您的代码将无缝运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2016-04-12
      • 2015-10-17
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 2022-01-12
      相关资源
      最近更新 更多