【问题标题】:How to store cookies in an Android WebView?如何在 Android WebView 中存储 cookie?
【发布时间】:2011-11-28 01:17:24
【问题描述】:

目前我正在尝试将 cookie 存储在我的 android 应用程序中。我的应用程序正在使用 android webview 加载网页。活动如下。

但是,我需要帮助才能在我的应用中存储 cookie。我正在加载的网页正在使用setcookie() 函数通过php 创建cookie。它在普通浏览器中运行良好,但我是一个初学者应用程序开发人员,它在我的 android WebView 中不起作用。

我需要你的帮助来用 php 存储 cookie(在加载的网页上)。

附:我希望 cookie 永远存在(如果可能的话)。

package com.stuff;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class Activity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        // Let's display the progress in the activity title bar, like the
        // browser app does.
        getWindow().requestFeature(Window.FEATURE_PROGRESS);

        WebView webview = new WebView(this);
        setContentView(webview);


        webview.getSettings().setJavaScriptEnabled(true);

        final Activity activity = this;
        webview.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
             // Activities and WebViews measure progress with different scales.
             // The progress meter will automatically disappear when we reach 100%
             activity.setProgress(progress * 1000);
        }
      });

webview.setWebViewClient(new WebViewClient() {

public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        //Users will be notified in case there's an error (i.e. no internet connection)
        Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
     //This will load the webpage that we want to see
      webview.loadUrl("http://www.need-cookies.com/");

   }
}

【问题讨论】:

    标签: java php android cookies android-webview


    【解决方案1】:

    看一下CookieSyncManager类,基本上可以这样:

    CookieSyncManager syncManager = CookieSyncManager.createInstance(webView.getContext());
    CookieManager cookieManager = CookieManager.getInstance();
    
    cookieManager.setCookie(); // Here your cookie
    syncManager.sync();
    

    【讨论】:

    • 谢谢,但我对 Android 完全陌生。抱歉,但我会在我的代码中的哪个位置添加它?此外,我将能够在 php 中创建我的 cookie 并使用 php 检索它们,对吗?谢谢,你摇滚!
    • 是的,使用 cookiemanager 实例,您也可以调用 getCookie();功能。您可以在创建 webView 实例后调用它: WebView webview = new WebView(this);
    • 所以澄清一下,我将能够使用这个 setcookie() 函数...w3schools.com/php/php_cookies.asp 在我的 php 脚本中,在这种情况下将位于 need-cookies.com
    • 要更清楚,need-cookies.com 可能是这个...
    猜你喜欢
    • 2017-11-03
    • 1970-01-01
    • 2011-07-21
    • 2012-01-13
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 2016-06-01
    相关资源
    最近更新 更多