您的位置:首页 > 移动开发

android开发中webview保存cookie问题的解决

2011-04-16 15:02 871 查看
最近被这个项目折腾死了

客户端登录---客户端九宫格---webview内容功能模块

实现思路:

登录还是调用原来的servlet进行验证

view plaincopy to clipboardprint?

List<NameValuePair> myList = new ArrayList<NameValuePair>();

myList.add(new BasicNameValuePair("STAFFID", username));

myList.add(new BasicNameValuePair("PWD", password));

HttpParams params = new BasicHttpParams();

DefaultHttpClient client = new DefaultHttpClient(params);

HttpPost post = new HttpPost(actionURL);

HttpResponse response = null;

BasicResponseHandler myHandler = new BasicResponseHandler();

String endResult = null;

try { post.setEntity(new UrlEncodedFormEntity(myList)); }

catch (UnsupportedEncodingException e)

{ e.printStackTrace(); }

try { response = client.execute(post); }

catch (ClientProtocolException e)

{ e.printStackTrace(); }

catch (IOException e)

{ e.printStackTrace(); }

验证成功后保存cookie并保存到SharedPreferences

//获取cookie信息

view plaincopy to clipboardprint?

List<Cookie> cookies = client.getCookieStore().getCookies();

if (cookies.isEmpty()) {

Log.i(TAG, "-------Cookie NONE---------");

} else {

for (int i = 0; i < cookies.size(); i ) {

//保存cookie

cookie = cookies.get(i);

Log.d(TAG, cookies.get(i).getName() "=" cookies.get(i).getValue() );

if(cookies.get(i).getName().equals("loginStaffId")) {

//保存登录信息,下次无需登录

String PREFS_NAME = "nma.qztc.com";

SharedPreferences settings = v.getContext().getSharedPreferences(PREFS_NAME, 0);

SharedPreferences.Editor editor = settings.edit();

editor.putString("staff_id", username);

editor.putString("pwd", password);

editor.commit();

return true;

}

-----------------------------------------------

将cookie信息带入到webview中,之前总是出现有时cookie读取成功有时不成功,找了半天发现将

cookieManager.removeSessionCookie();
这句去掉就好了,暂时还没有出现什么问题,由于原来的web应用是采用session验证,所以在读取cookie成功后也将session信息写入,这样就双保险了

//设置cookie信息

view plaincopy to clipboardprint?

Cookie sessionCookie = OnLoginListenerImpl.cookie;

CookieSyncManager.createInstance(this);

CookieManager cookieManager = CookieManager.getInstance();

if (sessionCookie != null) {

//cookieManager.removeSessionCookie();

cookieString = sessionCookie.getName() "=" sessionCookie.getValue() "; domain=" sessionCookie.getDomain();

Log.d("----nma cookie-----",cookieString);

//Log.d("----url-----",getString(getResources().getIdentifier(url,"string", getPackageName())));

cookieManager.setCookie(getString(getResources().getIdentifier(url,"string", getPackageName())), cookieString);

CookieSyncManager.getInstance().sync();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: