摘要: Andriod中WebView加载登录界面获取Cookie信息并同步保存,使第二次不用登录也可查看个人信息。
Android使用WebView加载登录的html界面,则通过登录成功获取Cookie并同步,可以是下一次不用登录也可以查看到个人信息,注:如果初始化加载登录,可通过缓存Cookie信息来验证是否要加载登录界面。Cookie信息包含了你登录的信息,打印是是这种格式 如下图:
包含各种编码,16进制等,可通过转码查看信息(包含当前城市,IP,个人相关信息等),转码后如图:
项目效果图:
代码:
public class MainActivity extends Activity {
public String urlSign = "http://xwwscs.com/app.php?platform=android&appkey=40a3e8e50fa27b8e6f1dd1a4b7454a0a&version=1.0&c=member&a=viewlogin";
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(MainActivity.this, Page.class));
}
});
}
@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
private void initView() {
webView = (WebView) findViewById(R.id.activity_webview);
webView.requestFocus();
webView.setHorizontalScrollBarEnabled(false);
webView.setVerticalScrollBarEnabled(false);
WebSettings web = webView.getSettings();
web.setJavaScriptEnabled(true);
web.setBuiltInZoomControls(true);
web.setSupportZoom(true);
web.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
web.setUseWideViewPort(true);
web.setLoadWithOverviewMode(true);
web.setSavePassword(true);
web.setSaveFormData(true);
webView.loadUrl(urlSign);
webView.setWebViewClient(new MyWebViewClient());
}
private class MyWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
public void onPageFinished(WebView view, String url) {
CookieManager cookieManager = CookieManager.getInstance();
String CookieStr = cookieManager.getCookie(url);
if (CookieStr != null) {
Log.i("cookie", CookieStr);
}
super.onPageFinished(view, url);
}
}
}
不要忘记在AndroidManifest.xml加权限哦!
<uses-permission android:name="android.permission.INTERNET"/>
源码点击下载