• 使用webview加载网页时session同步


    直接调用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;
              }});
  • 相关阅读:
    美国常青小组:“4+2”,成功的企业的普遍特征
    与你的商业伙伴建立信任关系的12条准则
    成功12级跳:你还是穷人只因为你没有立下成为富人的目标
    生日与谁共
    猎取人心的36条黄金法则
    谢谢你能为我落泪
    要锤炼出营销魔法,口碑营销“无招胜有招”
    怎样成为下一个比尔·盖茨?总结决定他成功的几大要素
    只要你能够幸福
    史玉柱:创业不是靠忽悠,我的最后四个忠告
  • 原文地址:https://www.cnblogs.com/seemann/p/4468701.html
Copyright © 2020-2023  润新知