zoukankan      html  css  js  c++  java
  • 使用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;
              }});
  • 相关阅读:
    AppDelegate减负之常用三方封装
    AppDelegate减负之常用三方封装
    基于AFN封装的带缓存的网络请求
    iOS-创建自己的日志系统
    UIImage 图片处理:截图,缩放,设定大小,存储
    /bin/sh^M: bad interpreter:解决办法
    mac上获取手机的uuid
    iOS PureLayout使用
    iOS集成友盟推送
    完全理解Python的 '==' 和 'is'
  • 原文地址:https://www.cnblogs.com/seemann/p/4468701.html
Copyright © 2011-2022 走看看