歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 網頁登錄 POST 請求 保存 COOKIE

Android 網頁登錄 POST 請求 保存 COOKIE

日期:2017/3/1 10:40:31   编辑:Linux編程

做的一個是要登錄自己的圖書館賬號,用於查看自己所借閱的書籍,

看了一下圖書館的代碼,發現是POST用戶名和密碼,

而在代碼實現主要有兩個難點:一、保存賬號密碼 二、保存Cookie

那麼 ,第一個可以使用之前提到過的Sharedpreference ,每次就直接從sharedpreference裡獲取賬號名和密碼就可以了,不需要每次都輸入

第二個怎麼獲得服務器的cookie呢,知道這次的session id

通過Httpclient 中的getcookiestore

  1. List<Cookie> cookies = httpclient.getCookieStore().getCookies();
  2. if (cookies.isEmpty()) {
  3. Log.i(TAG, "-------Cookie NONE---------");
  4. } else {
  5. for (int i = 0; i < cookies.size(); i ) {
  6. //保存cookie
  7. cookie = cookies.get(i);
  8. Log.d(TAG, cookies.get(i).getName() "=" cookies.get(i).getValue() );
  9. }

獲得了session id後,怎麼再添加到我們的POST或者GET請求裡面呢,

  1. HttpPost httpPost = new HttpPost(訪問地址);
  2. httpPost.setHeader("Cookie", "JSESSIONID=" + 我們在靜態變量裡存放的SessionId);
  3. HttpResponse httpResponse = httpclient.execute(httpPost);

  1. HttpGet request = new HttpGet(url+"?"+Params);
  2. request.setHeader("Cookie",Sessionid);

Copyright © Linux教程網 All Rights Reserved