使用WebView获取Cookie是一个很简单方便的方法,但是需要占用一些内存资源。在使用时应当注意防止内存泄漏,主要注意WebView的场景和对应的上下文。
WebView示例代码:
package com.lzy.webviewdemo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class MainActivity extends Activity {
private final static String TAG = "MainActivity";
//WebView相关配置
private final static String HOST_URL = "https://itorrents.org";
private final static String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36";
private final static String CF_CLEARENCE = "cf_clearance";
//磁力链接
private final static String HTTP_TEST = "https://itorrents.org/torrent/B415C913643E5FF49FE37D304BBB5E6E11AD5101.torrent";
private WebView webView;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.main_txt);
textView.setText("你看不见我");
initWebView();
}
@Override
protected void onDestroy() {
super.onDestroy();
webView.removeAllViews();
webView.destroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if(webView != null && webView.canGoBack()){
// goBack()表示返回WebView的上一页面
webView.goBack();
return true;
}
}
//结束当前页
return super.onKeyDown(keyCode, event);
}
public void initWebView(){
//xml加载
//webView = findViewById(R.id.main_web_view);
//推荐动态加载
webView = new WebView(MainActivity.this);
webView.setLayoutParams(new ViewGroup.LayoutParams(0, 0));
webView.setVisibility(View.INVISIBLE);
//基本设置
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口,如window.open(),默认为false
webSettings.setJavaScriptEnabled(true);//是否允许执行js,默认为false。设置true时,会提醒可能造成XSS漏洞
webSettings.setSupportZoom(true);//是否可以缩放,默认true
webSettings.setBuiltInZoomControls(true);
webSettings.setAppCacheEnabled(true);//是否使用缓存
webSettings.setDomStorageEnabled(true);//DOM Storage
webSettings.setUserAgentString(USER_AGENT);//设置用户代理
//网页自适应
webSettings.setUseWideViewPort(true);//将图片调整到适合webView的大小
webSettings.setLoadWithOverviewMode(true);//缩放至屏幕大小
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new NewWebViewClient());
//加载网页
webView.loadUrl(HOST_URL);
}
class NewWebViewClient extends WebViewClient{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
//添加Cookie获取操作
CookieManager cookieManager = CookieManager.getInstance();
final String cookieStr = cookieManager.getCookie(url);
Log.e(TAG, "Fetch Cookie: " + cookieStr);
if(cookieStr.contains(CF_CLEARENCE)){
textView.setText("Cookie已经获取到");
Thread workThread = new Thread(){
@Override
public void run() {
//Todo: 持久化Cookie到本地
...
}
};
workThread.start();
}
super.onPageFinished(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//返回值是true的时候WebView打开,为false则系统浏览器或第三方浏览器打开。
//如果要下载页面中的游戏或者继续点击网页中的链接进入下一个网页的话,重写此方法下,不然就会跳到手机自带的浏览器了,而不继续在你这个webview里面展现了
view.loadUrl(url);
return true;
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
}
}
}
XML文件中设置如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<!-- 若动态加载则不要在xml中定义 -->
<!--
<WebView
android:id="@+id/main_web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
>
</WebView>
-->
<TextView
android:id="@+id/main_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="14sp"
/>
</LinearLayout>