Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android本地登錄與WebView網頁登陸同步問題(cookie同步問題)

Android本地登錄與WebView網頁登陸同步問題(cookie同步問題)

編輯:關於Android編程

案例就是本地的登錄界面與網頁的登錄信息如何同步的問題:做混合開發的時候經常遇到的問題是,本地實現登錄界面,登錄成功後,使用webView加載網頁,這時網頁會提示需要登錄。這顯然是不友好的。

如何把本地的登錄信息與網頁的登錄同步呢?或者網頁登錄成功後,又如何同步到本地呢?本地如何獲取網頁的登錄信息呢?這裡你可以得到答案

下面就來實現這個功能。

這裡會遇到兩個問題。

1.客戶端登錄時如何取出cookie信息

2.如何把取出的cookie信息與webview同步傳遞給服務器

 

寫一個獲取cookie的類,本地登錄獲取cookie

package com.example.androidtest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.message.BasicNameValuePair;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

//WevView Cookie同步問題
public class HttpCookie extends Thread {
	private Handler handler;
	private String ASP_SessionId;
	public HttpCookie(Handler handler){
		this.handler = handler;
	}

	@Override
	public void run() {
		HttpClient client = new DefaultHttpClient();

		HttpPost post = new HttpPost("http://192.168.8.227:8080/manyiApp/WebCookieLoginCheckServlet");
		List list = new ArrayList();
		try {

			list.add(new BasicNameValuePair("name", "nates"));
			list.add(new BasicNameValuePair("age", "21"));

			Date sessionTime = new Date();  
			post.setEntity(new UrlEncodedFormEntity(list));
			HttpResponse response = client.execute(post);
			if(response.getStatusLine().getStatusCode()==200){
				AbstractHttpClient absClient = (AbstractHttpClient) client;
				List cookies = absClient.getCookieStore().getCookies();
				if (!cookies.isEmpty()) { 
					for(Cookie cookie:cookies){
						Log.i("TAG", cookie.toString());//獲取cookie信息並打印
						Message message = new Message();
						message.obj = cookie;
						handler.sendMessage(message);
						//return;
					}
				}

			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}
}

 

通過調用

HttpCookie mCookie = new HttpCookie(handler);
mCookie.start();

就可以運行獲取cookie信息了並通過handler發送獲取的cookie信息

下面是獲取handler中的cookie信息,並給webview設置cookie信息

package com.example.androidtest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class MainActivity extends Activity {
	private  WebView webView;  
	private Handler handler = new Handler(){
		@SuppressLint("NewApi") public void handleMessage(android.os.Message msg) {
			Log.i("TAG", "GethandlerCookies-----"+msg.obj.toString());
			CookieSyncManager.createInstance(MainActivity.this);
			CookieManager cookieManager = CookieManager.getInstance();
			cookieManager.setAcceptCookie(true);
			cookieManager.setCookie("http://192.168.8.227:8080/manyiApp", msg.obj.toString());//這樣設置url就可以同步manyApp目錄下所有頁面的cookie信息了
			CookieSyncManager.getInstance().sync();
			//webView.getSettings().setJavaScriptEnabled(true);//是支持JavaScript語言  
			webView.loadUrl("http://192.168.8.227:8080/manyiApp/Login.jsp");  
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		webView = (WebView) findViewById(R.id.myWebView);  

		webView.setWebViewClient(new MyWebViewClient());// webView.setWebViewClient()網頁加載默認是使用浏覽器的,這裡需要設置一下

		webView.setWebChromeClient(new WebChromeClient(){
			@Override
			public void onReceivedTitle(WebView view, String title) {
				// TODO Auto-generated method stub
				super.onReceivedTitle(view, title);
				Log.i("TAG", title);//獲取網頁title
			}

		});
		HttpCookie mCookie = new HttpCookie(handler);
		mCookie.start();//獲取cookie信息

	}
	/* 
	 * 去掉WebView顯示的網頁中的進度條和網址使更像客服端應用程序 
	 *  
	 * */  
	class MyWebViewClient extends WebViewClient{  
		@Override  
		public boolean shouldOverrideUrlLoading(WebView view, String url) {  

			view.loadUrl(url);//覆蓋浏覽器打方式,(不使用浏覽器打開頁面  )
			return true;  
		}
		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			super.onPageFinished(view, url);
			CookieManager cookieManager = CookieManager.getInstance();
			String CookieStr = cookieManager.getCookie(url);
			//Log.e("TAG", "Cookies = " + CookieStr);這裡可以實現,在網頁端登錄後獲取cookie信息並同步到本地登錄
			super.onPageFinished(view, url);
		}


	}  

	@Override  
	public boolean onKeyDown(int keyCode, KeyEvent event) {  
		if(keyCode == KeyEvent.KEYCODE_BACK&&webView.canGoBack()){  
			webView.goBack();//返回上個頁面  
			return true;  
		}  
		return super.onKeyDown(keyCode, event);//退出整個應用程序  
	}  

}  

 

下面是Web服務器端代碼

WebCookieLoginCheckServlet

package com.beijing.manyi.appservlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.xml.internal.txw2.Document;

/**
 * Servlet implementation class WebCookieLoginCheckServlet
 */
public class WebCookieLoginCheckServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public WebCookieLoginCheckServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("utf-8");
		request.setCharacterEncoding("utf-8");
		String name = request.getParameter("name");
		String age = request.getParameter("age");
		System.out.println("name:"+name+""+"age:"+age);
		Cookie c=new Cookie(name, age);//將得到的數據存入cookie 第一個參數是cookies中 name的值,第二個參數是value得值
		c.setMaxAge(600);
		//存儲
		response.addCookie(c);


		if(name.equals("nates")&&(age.equals("21"))){
			//	request.getSession().setAttribute("name", name);
			request.getRequestDispatcher("loginsuccess.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("Login.jsp").forward(request, response);
		}	        
	}

}


 

 

Login.jsp頁面,判斷cookie信息,如果符合就不用登錄了直接跳轉到登錄成功的頁面response.sendRedirect("loginsuccess.jsp");

但是貌似沒效果,js學的太爛,請大神指點哪裡錯了

<%@page import="javafx.scene.control.Alert"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

</head>
<%
	Cookie[] cookies = request.getCookies();
	if (cookies != null) {
		for (Cookie cookie : cookies) {
			if (cookie.getName().endsWith("nates")) {
				
				response.sendRedirect("loginsuccess.jsp");
				return;
			}
		}
	}
%>


<body>
	This is my Jsp pages
	<form action="WebCookieLoginCheckServlet" method="post">
		name:<input type="text" name="name"><br>age:<input
			type="text" name="age"><br> submit:<input type="submit"
			value="登錄">
</body>
</html>

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved