在Android WebView中设置Cookie

package com.test.myapplication;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import butterknife.Bind;
import butterknife.ButterKnife;

public class InfoActivity extends Activity {

    @Bind(R.id.web)
    WebView web;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.else_web_layout);
        ButterKnife.bind(this);

        configWebView(web, false);
        String url = "https://www.baidu.com/";
        synCookies(this, url, "uid=11");
        synCookies(this, url, "name=xyw");
        synCookies(this, url, "agent=android");
        synCookies(this, url, "age=20;sex=1;time=today");
        web.loadUrl(url );
    }

    /**
     * 设置Cookie
     *
     * @param context
     * @param url
     * @param cookie  格式:uid=21233 如需设置多个,需要多次调用
     */
    public void synCookies(Context context, String url, String cookie) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(url, cookie);//cookies是在HttpClient中获得的cookie
        CookieSyncManager.getInstance().sync();
    }

    /**
     * 清除Cookie
     *
     * @param context
     */
    public static void removeCookie(Context context) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        CookieSyncManager.getInstance().sync();
    }


    protected void configWebView(WebView webView, boolean needCache) {

        if (!needCache) {
            webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        }

        webView.getSettings().setJavaScriptEnabled(true);
        //启用数据库
        webView.getSettings().setDatabaseEnabled(true);
        //设置定位的数据库路径
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        webView.getSettings().setGeolocationDatabasePath(dir);
        //启用地理定位
        webView.getSettings().setGeolocationEnabled(true);
        //开启DomStorage缓存
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.setWebViewClient(new WebViewClient(){});
        webView.setWebChromeClient(new WebChromeClient());
    }
}

查看请求报文如下:设置cookie前


 
  


查看请求报文如下:设置cookie后,设置Cookie成功

在Android WebView中设置Cookie_第1张图片


最后需注意:如果需要设置多个Cookie,需要多次设置。不能synCookies(this, url, "age=20;sex=1;time=today");,这样只能设置第一个值age=20.

你可能感兴趣的:(android)