dongluni0568 2011-11-28 01:17
浏览 92
已采纳

如何在Android WebView中存储cookie?

Currently I'm trying to store cookies in my android app. My app is loading a web page using the android webview. The activity is below.

But, I need help to store cookies in my app. The web page I'm loading is creating the cookies with php using the setcookie() function. It works fine in a regular browser, but I'm a beginner app developer and it doesn't work in my android WebView.

I need your help to store the cookie with php (on the loaded web page).

P.S. I want the cookie to last forever (if possible).

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/");

   }
}
  • 写回答

1条回答 默认 最新

  • douhulao7642 2011-11-28 01:23
    关注

    Take a look at the CookieSyncManager class, basically you can do this:

    CookieSyncManager syncManager = CookieSyncManager.createInstance(webView.getContext());
    CookieManager cookieManager = CookieManager.getInstance();
    
    cookieManager.setCookie(); // Here your cookie
    syncManager.sync();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化