【问题标题】:WebView cookies in a HTTP RequestHTTP 请求中的 WebView cookie
【发布时间】:2013-01-06 01:47:31
【问题描述】:

是否可以在 HTTP 请求中使用 WebView 的 cookie?如果是,我该怎么做?

谢谢

【问题讨论】:

    标签: android


    【解决方案1】:

    CookieManager 就是您要找的东西!

    CookieSyncManager.createInstance(context)
    

    创建管理器

    CookieSyncManager.getInstance().startSync()
    

    在Activity.onResume()中,调用

     CookieSyncManager.getInstance().stopSync()
    

    在 Activity.onPause() 中。

    要获得即时同步而不是等待计时器触发,主机可以调用

     CookieSyncManager.getInstance().sync()
    

    请注意,即使 sync() 也是异步发生的,所以不要在您的活动正在关闭时执行此操作。

    以下是您可能会如何使用它:

    // use cookies to remember a logged in status   
    CookieSyncManager.createInstance(this);
    CookieSyncManager.getInstance().startSync();
    WebView webview = new WebView(this);
    webview.getSettings().setJavaScriptEnabled(true);
    setContentView(webview);      
    webview.loadUrl([MY URL]);
    

    Referenced from this question

    编辑: 如果你想用 HttpClient 来做,你需要创建一个 HttpContext。

    // Create a local instance of cookie store
    CookieStore cookieStore = new BasicCookieStore();
    
    // Create local HTTP context
    HttpContext localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    
    HttpGet httpget = new HttpGet("http://www.google.com/"); 
    
    System.out.println("executing request " + httpget.getURI());
    
    // Pass local context as a parameter
    HttpResponse response = httpclient.execute(httpget, localContext);
    

    Referenced from this question

    【讨论】:

    • 嗯,我可以将它们添加到 DefaultHttpClient 中吗?
    • 我想你不明白我的意思。我想在我的 http 客户端中使用我的 webview 的 cookie。造成误会请见谅
    • 它在某种程度上是技术的组合,在这里查看stackoverflow.com/questions/8080761/…
    猜你喜欢
    • 1970-01-01
    • 2015-10-29
    • 2010-11-26
    • 1970-01-01
    • 2017-03-29
    • 2017-03-10
    • 1970-01-01
    • 2018-12-19
    • 2012-06-07
    相关资源
    最近更新 更多