Android webView 获取、设置 cookie的方法

做android项目难免遇到这种情况,需使用webview加载网页,并且获取cookie。或者需要设置自己的请求cookie蔡翁正常加载网页。下面分别介绍一下android 中 webview的使用方法。

1.获取url中的cookie:

    方法一:我们需要自己写一个cookie管理类:MyWebViewClient

public class MyWebViewClient extends WebViewClient {
    String url;
    WebView view;
    Activity activity;
    TextView textView;
    public MyWebViewClient(Activity activity)
    {
      //  this.textView =textView;
        this.activity =activity;
    }

    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

    public void onPageFinished(WebView view, String url) {
        CookieManager cookieManager = CookieManager.getInstance();
        String CookieStr = cookieManager.getCookie(url);
        Common.cookie = CookieStr;
        Toast.makeText(activity,CookieStr,Toast.LENGTH_SHORT).show();
        super.onPageFinished(view, url);
    }

}

在主Activity方法中调用:

public class MainActivity extends Activity {
    private WebView mWebView;
    private MainActivity self;
    private String url ="https://www.baidu.com";//带cookie的页面url
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        self = MainActivity.this;
        mWebView = (WebView) findViewById(R.id.webview_forshow);
        mWebView.getSettings().setAppCacheEnabled(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDatabaseEnabled(false);
        mWebView.getSettings().setDomStorageEnabled(false );
        mWebView.getSettings().setGeolocationEnabled(false);
//        mWebView.getSettings().setPluginsEnabled(false);
        mWebView.getSettings().setSaveFormData(false);
        mWebView.getSettings().setSavePassword(false);
        mWebView.getSettings().setJavaScriptEnabled(true); ///------- 设置javascript 可用
        mWebView.loadUrl(url);
        mWebView.setWebChromeClient(new WebChromeClient()
        {
            @Override
            public void onProgressChanged(WebView view, int newProgress)
            {
                super.onProgressChanged(view, newProgress);
                view.requestFocus();
            }
        });
        mWebView.setWebViewClient(new MyWebViewClient(self));
      
    }


}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webview_forshow"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></WebView>
</LinearLayout>

    方法二

CookieManager cookieManager = CookieManager.getInstance();
String cookieStr  = cookieManager.getCookie(url);

注意:android需要连接网络的时候,要给予网络请求权限:

 <!-- 允许应用程序联网,以便向我们的服务器端发送数据 -->
    <uses-permission android:name="android.permission.INTERNET" />
2.获取url中设置请求cookie:

   在Load url之前调用 setCookies 方法:

/**
 * 设置Cookie
 *
 * @param url
 */
private void setCookies(String url) {
    if (!TextUtils.isEmpty(strCookies)) {
        String arrayCookies[] = strCookies.split(";");
        if (arrayCookies != null && arrayCookies.length > 0) {
            for (String cookie : arrayCookies) {
               // synCookies(url, cookie);
                synCookies(this, url, cookie);
            }
        }
    }
}

/**
 * 同步Cookie
 *
 * @param url
 * @param cookie 格式:uid=21233 如需设置多个,需要多次调用
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void synCookies(String url, String cookie) {
    try {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(url, cookie);//cookies是在HttpClient中获得的cookie
        cookieManager.flush();
    }catch (Exception e){
        ToastUtil.showMessage(getString(com.neusoft.phone.xinhua.newsedit.R.string.no_support));
    }
}

/**
 * 设置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+";Domain=hotspot.******;Path=/");//cookies格式自定义
    CookieSyncManager.getInstance().sync();
}

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


猜你喜欢

转载自blog.csdn.net/qq_35573326/article/details/80013424