[Android執行個體] 關於webview如何自動登入儲存登入資訊

來源:互聯網
上載者:User

這個是自己總結出來的經驗,求版主推薦,求申精! 
使用者名稱密碼登入驗證後儲存Session

// 你的URL                HttpPost httppost = new HttpPost(Constants.ServerUrl.WEB_URL + url);                try {                         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);                         // Your DATA                        nameValuePairs.add(new BasicNameValuePair("UserName", map                                        .get("UserName")));                         nameValuePairs.add(new BasicNameValuePair("Password", map                                        .get("Password")));                         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));                         HttpResponse response;                         response = httpclient.execute(httppost);                        if (response.getStatusLine().getStatusCode() == 200) {                                // 獲得響應                                String result = EntityUtils.toString(response.getEntity());                                // SharedPreferences preferences = context.getSharedPreferences(                                // "login", Context.MODE_PRIVATE);                                // Editor editor = preferences.edit();                                // String handlers = "";                                String cookie = "";                                Date sessionTime = new Date();                                List<Cookie> cookies = httpclient.getCookieStore().getCookies();                                if (!cookies.isEmpty()) {                                        for (int i = 0; i < cookies.size(); i++) {                                                cookie = cookies.get(i).getName() + "="                                                                + cookies.get(i).getValue() + ";domain="                                                                + cookies.get(i).getDomain();                                                ;                                                sessionTime = cookies.get(i).getExpiryDate();                                        }                                }                               //儲存session                                PersistentConfig config = new PersistentConfig(context);                                config.setCookie(cookie);                                 config.setSessionTime(sessionTime.getTime());                                // for (int i = 0; i < response.getAllHeaders().length; i++) {                                // if (response.getAllHeaders()<i>.toString().contains(                                // "set-cookie")) {                                // handlers += response.getAllHeaders()<i>.toString();                                // break;                                // }                                // }                                //                                // editor.putString("cookies",                                // response.getHeaders("Set-Cookie")[0].toString());                                // editor.commit();                                return result;                        }                 } catch (ClientProtocolException e) {                         // TODO Auto-generated catch block                         e.printStackTrace();                 } catch (IOException e) {                         // TODO Auto-generated catch block                         e.printStackTrace();                 }

如何在Webview請求網站時使用Session

//webview初始化的時候調用          main_view = (WebView) findViewById(R.id.main_webview);          new WebViewTask().execute();                     private class WebViewTask extends AsyncTask<Void, Void, Boolean> {                  String sessionCookie;                  CookieManager cookieManager;                     @Override                  protected void onPreExecute() {                          CookieSyncManager.createInstance(MainActivity.this);                          cookieManager = CookieManager.getInstance();                             sessionCookie = new PersistentConfig(getApplicationContext())                                          .getCookieString();                          if (sessionCookie != null) {                                  // delete old cookies                                  cookieManager.removeSessionCookie();                          }                          super.onPreExecute();                  }                     protected Boolean doInBackground(Void... param) {                          // this is very important - THIS IS THE HACK                          SystemClock.sleep(1000);                          return false;                  }                     @Override                  protected void onPostExecute(Boolean result) {                          if (sessionCookie != null) {                                  cookieManager.setCookie(Constants.ServerUrl.WEB_URL,                                                  sessionCookie);                                  CookieSyncManager.getInstance().sync();                          }                          main_view.setScrollbarFadingEnabled(true);                          main_view.getSettings().setPluginsEnabled(true);                          main_view.getSettings().setPluginState(PluginState.ON);                          main_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);                          WebSettings webSettings = main_view.getSettings();                          webSettings.setJavaScriptEnabled(true);                          // 設定可以訪問檔案                          webSettings.setAllowFileAccess(true);                          // 設定支援縮放                          webSettings.setBuiltInZoomControls(true);                          main_view.setWebViewClient(new WebViewClient() {                                  @Override                                  public void onPageStarted(WebView view, String url,                                                  Bitmap favicon) {                                          // TODO Auto-generated method stub                                           super.onPageStarted(view, url, favicon);                                  }                                     @Override                                  public void onLoadResource(WebView view, String url) {                                          // history();                                   }                          });                          main_view.setWebChromeClient(new WebChromeClient() {                                  public void onProgressChanged(WebView view, int progress) {                                          //Change                                  }                          });                          ShowUrlView(Constants.ServerUrl.INDEX);                  }          } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.