码迷,mamicode.com
首页 > Web开发 > 详细

使用webview加载网页时session同步

时间:2015-04-30 15:43:05      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

直接调用Android的webview加载URL时,由于需要登录的session导致URL无法显示,解决方案是在需要访问的URL中加session:

         String reporturl = "http://xxx.xxx.xx";
	 CookieSyncManager.createInstance(getApplication());
 	 CookieManager cookieManager = CookieManager.getInstance();
	 CookieSyncManager.getInstance().startSync();
	 List<Cookie> sessionCookie = MyApplication.getAppCookie();
	 String re= cookieManager.getCookie(reporturl);
	   if (sessionCookie != null) {
 		  for (int i = 0; i < sessionCookie.size(); i++) {
	            Cookie cookie = sessionCookie.get(i);
	            String cookieString=cookie.getName() + "=" + cookie.getValue()    //path与Domain必须加上
	                    + "; path=" + cookie.getPath()
	                    + "; domain=" + cookie.getDomain();
	            cookieManager.setCookie(reporturl, cookieString);
	        }
		 String re2= cookieManager.getCookie(reporturl);
	         CookieSyncManager.getInstance().sync();
	 }
	

 其中sessionCookie是在登录时放入MyApplication中的:

         HttpPost httpPost = new HttpPost(url);   
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); httpClient.getParams().setIntParameter("http.socket.timeout", 3000); HttpResponse response = httpClient.execute(httpPost); String result = EntityUtils.toString(response.getEntity(),HTTP.UTF_8); Log.d(TAG, "HTTP Response: " + result); List<Cookie> cookies = httpClient.getCookieStore().getCookies(); MyApplication.setAppCookie(cookies);

然后可以加载URL了:

      myWebView.getSettings().setJavaScriptEnabled(true);  
      myWebView.getSettings().setSupportZoom(true); 
      myWebView.getSettings().setAppCacheEnabled(true);
      //设置缓存模式
      myWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
      myWebView.loadUrl(reporturl);
      myWebView.getSettings().setBuiltInZoomControls(true);
      myWebView.getSettings().setUseWideViewPort(true);
      myWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
      myWebView.getSettings().setLoadWithOverviewMode(true);
      myWebView.setWebViewClient(new WebViewClient(){
          public boolean shouldOverrideUrlLoading(WebView view, String url) {  //重写此方法表明点击网页里面的链接还是在当前的webview里跳转,不跳到浏览器那边
               view.loadUrl(url);
               return true;
          }});

 

使用webview加载网页时session同步

标签:

原文地址:http://www.cnblogs.com/seemann/p/4468701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!