private void configureCookies(String url) {

    final CookieManager cookieManager = CookieManager.getInstance();

    String cookieHeader = cookieManager.getCookie(url);

    if (cookieHeader != null) {

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        cookieManager.removeAllCookies(null);
      } else {
        cookieManager.removeAllCookie();
      }

      // We want to always enter in a not-logged-in state.  If the webview has a cookie indicating
      // it has logged in then it will bypass login and go to the .com site.  Remove that cookie.
      // Also, with CookieManager there is no direct way to remove a cookie.  We just iterate the
      // full set and only add back the cookies we want.
      String[] cookies = cookieHeader.split(";");
      for (String cookie : cookies) {
        if (!cookie.trim().startsWith(ACCESS_TOKEN_COOKIE + '=')) {
          cookieManager.setCookie(url, cookie);
        }
      }
    }

    // Add the small view cookie.
    // TODO: In a future release, determine the device size (phone v. tablet) and set the correct
    // cookie value for size
    cookieManager.setCookie(url, "idl_icc=s");

    Log.e(TAG, "configureCookies cookie manager : " + cookieManager.getCookie(url));
  }
 /**
  * Removes cookie by name for a URL.
  *
  * @param url to remove cookie for
  * @param name of the cookie to remove
  */
 public void remove(String url, String name) {
   List<String> domains;
   try {
     domains = getDomainsFromUrl(new URL(url));
   } catch (MalformedURLException e) {
     throw new WebDriverException("Error while adding cookie. " + e);
   }
   for (String domain : domains) {
     List<Cookie> cookies = getCookies(domain);
     for (Cookie c : cookies) {
       if (c.getName().equals(name)) {
         cookies.remove(c);
         // To remove a cookie we set the date somewhere in the past.
         cookieManager.setCookie(
             domain,
             String.format(
                 "%s=; expires=%s",
                 name,
                 new SimpleDateFormat(COOKIE_DATE_FORMAT)
                     .format(System.currentTimeMillis() - 500)));
         break;
       }
     }
   }
   cookieManager.removeExpiredCookie();
 }
Example #3
0
  @SuppressWarnings("deprecation")
  private void setCookie(Context context) {
    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();
    cookieManager.setAcceptCookie(true);
    for (int i = 0; i < cookies.size(); i++) {
      Cookie cookie = cookies.get(i);
      String cookieName = cookie.getName();
      String cookieValue = cookie.getValue();
      String domainString = cookie.getDomain();
      //			Log.i("FRAGHOME",cookieName);
      //			Log.i("FRAGHOME",cookieValue);
      //			Log.i("FRAGHOME",domainString);
      if (!cookieName.isEmpty() && !cookieValue.isEmpty() && !domainString.isEmpty()) {
        cookieManager.setCookie(domainString, cookieName + "=" + cookieValue);
      }
    }

    //		cookieManager.setCookie(baseURL, "uid=123");
    CookieSyncManager.getInstance().sync();
    if (cookieManager.getCookie(devbaseURL) != null) {
      System.out.println(cookieManager.getCookie(devbaseURL));
    }
    //		webview.loadUrl(baseURL+"?app-get_top_cate");
    //		System.out.println(cookieManager.getCookie(baseURL));
  }
  public String getCookie(String url) {
    final CookieManager cookieManager = CookieManager.getInstance();
    String cookie = cookieManager.getCookie(url);

    if (cookie == null || cookie.length() == 0) {
      final HttpHead head = new HttpHead(url);
      HttpEntity entity = null;
      try {
        final HttpResponse response = HttpManager.execute(head);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
          entity = response.getEntity();

          final Header[] cookies = response.getHeaders("set-cookie");
          for (Header cooky : cookies) {
            cookieManager.setCookie(url, cooky.getValue());
          }

          CookieSyncManager.getInstance().sync();
          cookie = cookieManager.getCookie(url);
        }
      } catch (IOException e) {
        Log.e(LOG_TAG, "Could not retrieve cookie", e);
      } finally {
        if (entity != null) {
          try {
            entity.consumeContent();
          } catch (IOException e) {
            Log.e(LOG_TAG, "Could not retrieve cookie", e);
          }
        }
      }
    }

    return cookie;
  }
 /** 同步一下cookie */
 public static void synCookies(Context context, String url, String cookies) {
   CookieSyncManager.createInstance(context);
   CookieManager cookieManager = CookieManager.getInstance();
   cookieManager.setAcceptCookie(true);
   cookieManager.removeSessionCookie(); // 移除
   cookieManager.setCookie(url, cookies); // cookies是在HttpClient中获得的cookie
   CookieSyncManager.getInstance().sync();
 }
Example #6
0
 /** 同步一下cookie */
 public static void synCookies(Context context, String url) {
   CookieSyncManager.createInstance(context);
   CookieManager cookieManager = CookieManager.getInstance();
   cookieManager.setAcceptCookie(true);
   cookieManager.removeSessionCookie(); // 移除
   String token = SharedPrefsUtil.getValue(Constants.TOKEN, null);
   cookieManager.setCookie(url, "token=" + token + ";path=/"); // cookies是在HttpClient中获得的cookie
   CookieSyncManager.getInstance().sync();
 }
Example #7
0
 public static void setCookie(Context context) {
   if (!StringUtil.isEmpty(CustomerUtil.getAuthenTick())) {
     CookieSyncManager.createInstance(context);
     CookieManager cookieManager = CookieManager.getInstance();
     cookieManager.setAcceptCookie(true);
     cookieManager.setCookie("http://www.kjt.com/", CustomerUtil.getAuthenTick() + ";path=/");
     CookieSyncManager.getInstance().sync();
   }
 }
 public void testb3167208() throws Exception {
   String uri = "http://host.android.com/path/";
   // note the space after the domain=
   String problemCookie = "foo=bar; domain= .android.com; path=/";
   mCookieManager.setCookie(uri, problemCookie);
   String cookie = mCookieManager.getCookie(uri);
   assertNotNull(cookie);
   assertTrue(cookie.contains("foo=bar"));
 }
 /**
  * Adds a cookie to a URL domain.
  *
  * @param url to add the cookie to
  * @param cookie Cookie to be added
  */
 public void addCookie(String url, Cookie cookie) {
   URL urlObj;
   try {
     urlObj = new URL(url);
   } catch (MalformedURLException e) {
     throw new WebDriverException("Error while adding cookie. ", e);
   }
   String domain = "http://" + urlObj.getHost() + cookie.getPath();
   if (!domain.endsWith("/")) {
     domain = domain + "/";
   }
   cookieManager.setCookie(domain, stringifyCookie(cookie));
 }
Example #10
0
 protected void onPostExecute(String result) {
   CookieSyncManager.createInstance(getApplicationContext());
   CookieSyncManager.getInstance().resetSync();
   CookieSyncManager.getInstance().startSync();
   CookieManager manager = CookieManager.getInstance();
   manager.acceptCookie();
   manager.setAcceptCookie(true);
   manager.setCookie("https://login.gatech.edu/cas/login", "Set-Cookie");
   manager.setCookie("https://t-square.gatech.edu/portal/pda", "Set-Cookie");
   manager.setCookie("https://t-square.gatech.edu/sakai-login-tool/container", "Set-Cookie");
   wv.clearHistory();
   manager.removeAllCookie();
   manager.setCookie(
       contentLink, getSharedPreferences(TsquareMain.MENU_LIST, 0).getString("TsquareJS", null));
   manager.setCookie(
       contentLink, getSharedPreferences(TsquareMain.MENU_LIST, 0).getString("Bigip", null));
   wv.loadUrl(contentLink);
   wv.setVisibility(View.VISIBLE);
   if (menuItem != null) {
     menuItem.collapseActionView();
     menuItem.setActionView(null);
   }
 }
Example #11
0
 public void addCookie(Cookie paramCookie) {
   String str1 = paramCookie.getName();
   this.mCookies.put(str1, paramCookie);
   SharedPreferences.Editor localEditor = this.mCookiePrefs.edit();
   localEditor.putString("names", TextUtils.join(",", this.mCookies.keySet()));
   localEditor.putString("cookie_" + str1, encodeCookie(new SerializableCookie(paramCookie)));
   localEditor.commit();
   CookieManager localCookieManager = CookieManager.getInstance();
   String str2 =
       paramCookie.getName()
           + "="
           + paramCookie.getValue()
           + "; domain="
           + paramCookie.getDomain();
   localCookieManager.setCookie(paramCookie.getDomain(), str2);
   CookieSyncManager.getInstance().sync();
 }
Example #12
0
  public RegisterResponse signup(final String username, final String password, final String email) {
    final ContentValues values = new ContentValues();
    values.put(APIConstants.PARAMETER_USERNAME, username);
    values.put(APIConstants.PARAMETER_PASSWORD, password);
    values.put(APIConstants.PARAMETER_EMAIL, email);
    final APIResponse response = post(APIConstants.URL_SIGNUP, values);
    RegisterResponse registerResponse =
        ((RegisterResponse) response.getResponse(gson, RegisterResponse.class));
    if (!response.isError()) {
      PrefsUtils.saveLogin(context, username, response.getCookie());

      CookieSyncManager.createInstance(context.getApplicationContext());
      CookieManager cookieManager = CookieManager.getInstance();

      cookieManager.setCookie(APIConstants.COOKIE_DOMAIN, response.getCookie());
      CookieSyncManager.getInstance().sync();
    }
    return registerResponse;
  }
Example #13
0
  @Override
  public void onLetterSend(int id, String guid) {

    if (id > 1) {

      AlertDialog alertDialog = new AlertDialog.Builder(this).create();
      alertDialog.setTitle("Send successful");
      alertDialog.setMessage("Your letter was sent.");

      alertDialog.setButton(
          "Yay",
          new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

              // here you can add functions

            }
          });

      alertDialog.show();

      httpClient = new DefaultHttpClient();
      List<Cookie> cookies = httpClient.getCookieStore().getCookies();
      for (int i = 0; i < cookies.size(); i++) {
        cookie = cookies.get(i);
      }

      // ------- Web Browser activity
      CookieSyncManager.createInstance(this);
      CookieManager cookieManager = CookieManager.getInstance();

      cookieManager.setCookie(
          "www.letterstocrushes.com", guid + "=1; domain=www.letterstocrushes.com");
      CookieSyncManager.getInstance().sync();

      mAdapter = new MyAdapter(getSupportFragmentManager(), "letter/" + Integer.toString(id), "");
      mPager = (ViewPager) findViewById(R.id.pager);
      mPager.setAdapter(mAdapter);

      mPager.setCurrentItem(1);
    }
  }
  @TestTargets({
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "hasCookies",
        args = {}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "removeAllCookie",
        args = {})
  })
  @ToBeFixed(explanation = "CookieManager.hasCookies() should also count cookies in RAM cache")
  public void testCookieManager() {
    // enable cookie
    mCookieManager.setAcceptCookie(true);
    assertTrue(mCookieManager.acceptCookie());

    // first there should be no cookie stored
    assertFalse(mCookieManager.hasCookies());

    String url = "http://www.example.com";
    String cookie = "name=test";
    mCookieManager.setCookie(url, cookie);
    assertEquals(cookie, mCookieManager.getCookie(url));

    // sync cookie from RAM to FLASH, because hasCookies() only counts FLASH cookies
    CookieSyncManager.getInstance().sync();
    new DelayedCheck(TEST_DELAY) {
      @Override
      protected boolean check() {
        return mCookieManager.hasCookies();
      }
    }.run();

    // clean up all cookies
    mCookieManager.removeAllCookie();
    new DelayedCheck(TEST_DELAY) {
      @Override
      protected boolean check() {
        return !mCookieManager.hasCookies();
      }
    }.run();
  }
Example #15
0
  public LoginResponse signup(final String username, final String password, final String email) {
    final APIClient client = new APIClient(context);
    final ContentValues values = new ContentValues();
    values.put(APIConstants.PARAMETER_USERNAME, username);
    values.put(APIConstants.PARAMETER_PASSWORD, password);
    values.put(APIConstants.PARAMETER_EMAIL, email);
    final APIResponse response = client.post(APIConstants.URL_SIGNUP, values);
    if (response.responseCode == HttpStatus.SC_OK && !response.hasRedirected) {
      LoginResponse loginResponse = gson.fromJson(response.responseString, LoginResponse.class);
      PrefsUtils.saveLogin(context, username, response.cookie);

      CookieSyncManager.createInstance(context.getApplicationContext());
      CookieManager cookieManager = CookieManager.getInstance();

      cookieManager.setCookie(".newsblur.com", response.cookie);
      CookieSyncManager.getInstance().sync();

      return loginResponse;
    } else {
      return new LoginResponse();
    }
  }
  private static void clearCookiesForDomain(Context context, String domain) {
    // This is to work around a bug where CookieManager may fail to instantiate if CookieSyncManager
    // has never been created.
    CookieSyncManager syncManager = CookieSyncManager.createInstance(context);
    syncManager.sync();

    CookieManager cookieManager = CookieManager.getInstance();

    String cookies = cookieManager.getCookie(domain);
    if (cookies == null) {
      return;
    }

    String[] splitCookies = cookies.split(";");
    for (String cookie : splitCookies) {
      String[] cookieParts = cookie.split("=");
      if (cookieParts.length > 0) {
        String newCookie = cookieParts[0].trim() + "=;expires=Sat, 1 Jan 2000 00:00:01 UTC;";
        cookieManager.setCookie(domain, newCookie);
      }
    }
    cookieManager.removeExpiredCookie();
  }
Example #17
0
  /**
   * android中HttpClient和WebView共享session的解决办法
   *
   * <p>android开始项目中,通常会遇到既使用HttpClient,又使用WebView的情况。一个典型的例子是,使用HttpClient登录,WebView展示登录后的某些页面,这个时候,如果直接不加任何处理的话会发现在使用WebView展示的时候,会提示没有登录你的应用系统,造成这种结果的原因就是使用HttpClient登录的session和WebView访问服务器的session并不是同一个,解决办法如下。
   * WebView代码
   *
   * @param url4load
   */
  protected void session(String url4load) {
    // String url4load = "登录域名下你要访问的地址";
    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    //		Cookie sessionCookie = HttpStreamThread.sessionCookie;//this.sessionCookie;
    //		if (sessionCookie != null) {
    //			String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + ";
    // domain=" + sessionCookie.getDomain();
    //			cookieManager.setCookie(url4load, cookieString);
    //			CookieSyncManager.getInstance().sync();
    //		}

    CookieStore cookieStore = HttpStreamThread.cookieStore;
    if (null != cookieStore) {
      List<Cookie> cookies = cookieStore.getCookies();
      StringBuilder sb = new StringBuilder();
      if (null != cookies) {
        for (int i = 0; i < cookies.size(); i++) {
          // 这里是读取Cookie['PHPSESSID']的值存在静态变量中,保证每次都是同一个值
          //                if (cookie_key.equals(cookies.get(i).getName())) {
          //                	cookie_value = cookies.get(i).getValue();
          //                	sessionCookie = cookies.get(i);
          //                }
          sb.append(
              cookies.get(i).getName()
                  + "="
                  + cookies.get(i).getValue()
                  + "; domain="
                  + cookies.get(i).getDomain()
                  + " ");
        }
      }

      cookieManager.setCookie(url4load, sb.toString());
      CookieSyncManager.getInstance().sync();
    }
  }
  @TestTargets({
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "setAcceptCookie",
        args = {boolean.class}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "acceptCookie",
        args = {}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "setCookie",
        args = {String.class, String.class}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "getCookie",
        args = {String.class}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "removeAllCookie",
        args = {})
  })
  public void testAcceptCookie() throws Exception {
    mCookieManager.removeAllCookie();
    mCookieManager.setAcceptCookie(false);
    assertFalse(mCookieManager.acceptCookie());
    assertFalse(mCookieManager.hasCookies());

    CtsTestServer server = new CtsTestServer(getActivity(), false);
    String url = server.getCookieUrl("conquest.html");
    loadUrl(url);
    assertEquals(null, mWebView.getTitle()); // no cookies passed
    Thread.sleep(TEST_DELAY);
    assertNull(mCookieManager.getCookie(url));

    mCookieManager.setAcceptCookie(true);
    assertTrue(mCookieManager.acceptCookie());

    url = server.getCookieUrl("war.html");
    loadUrl(url);
    assertEquals(null, mWebView.getTitle()); // no cookies passed
    waitForCookie(url);
    String cookie = mCookieManager.getCookie(url);
    assertNotNull(cookie);
    // 'count' value of the returned cookie is 0
    final Pattern pat = Pattern.compile("count=(\\d+)");
    Matcher m = pat.matcher(cookie);
    assertTrue(m.matches());
    assertEquals("0", m.group(1));

    url = server.getCookieUrl("famine.html");
    loadUrl(url);
    assertEquals("count=0", mWebView.getTitle()); // outgoing cookie
    waitForCookie(url);
    cookie = mCookieManager.getCookie(url);
    assertNotNull(cookie);
    m = pat.matcher(cookie);
    assertTrue(m.matches());
    assertEquals("1", m.group(1)); // value got incremented

    url = server.getCookieUrl("death.html");
    mCookieManager.setCookie(url, "count=41");
    loadUrl(url);
    assertEquals("count=41", mWebView.getTitle()); // outgoing cookie
    waitForCookie(url);
    cookie = mCookieManager.getCookie(url);
    assertNotNull(cookie);
    m = pat.matcher(cookie);
    assertTrue(m.matches());
    assertEquals("42", m.group(1)); // value got incremented

    // clean up all cookies
    mCookieManager.removeAllCookie();
  }
Example #19
0
  @Override
  protected void onResume() {
    super.onResume();
    subjectName = getIntent().getExtras().getString("subjectName");
    boardName = getIntent().getExtras().getString("boardName");
    contentName = getIntent().getExtras().getString("contentName");
    contentLink = getIntent().getExtras().getString("contentLink");
    setTitle(contentName);

    if (isNetworkConnected()) {
      CookieSyncManager.createInstance(getApplicationContext());
      CookieSyncManager.getInstance().startSync();
      manager = CookieManager.getInstance();
      manager.acceptCookie();
      manager.setAcceptCookie(true);
      manager.removeAllCookie();
      SharedPreferences menuSp = getSharedPreferences(TsquareMain.MENU_LIST, 0);
      manager.setCookie(contentLink, menuSp.getString("TsquareJS", null));
      manager.setCookie(contentLink, menuSp.getString("Bigip", null));
      CookieSyncManager.getInstance().sync();

      wv = (WebView) findViewById(R.id.webView);
      wv.setWebViewClient(
          new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
              super.onPageFinished(view, url);
              if (menuItem != null) {
                menuItem.collapseActionView();
                menuItem.setActionView(null);
                new ToastRun("Done :)").run();
              }
            }
          });
      wv.setPadding(5, 0, 5, 0);
      try {
        Log.d("cookie is ", manager.getCookie(contentLink));
        if (new LoginCheck(this, new URL(contentLink), manager.getCookie(contentLink))
                .execute()
                .get()
            == 0) wv.loadUrl(contentLink);
        else {
          wv.setVisibility(View.INVISIBLE);
          new TestTask(this).execute();
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (ExecutionException e) {
        e.printStackTrace();
      } catch (MalformedURLException e) {
        e.printStackTrace();
      }
    } else if (!((WifiManager) getSystemService(Context.WIFI_SERVICE)).isWifiEnabled()) {
      new AlertDialog.Builder(this)
          .setTitle("Network status alert")
          .setMessage("Network is not connected.\nWould you like to enable the WI-FI?")
          .setPositiveButton(
              "Yes",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  finish();
                  WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                  wifiManager.setWifiEnabled(true);
                }
              })
          .setNegativeButton(
              "No",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  finish();
                }
              })
          .show();
    } else { // WIFI is on and network is not connected
      new AlertDialog.Builder(this)
          .setTitle("Network status alert")
          .setMessage("Network is not connected with WI-FI.\nPlease check your network.")
          .setPositiveButton(
              "Ok",
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                  finish();
                }
              })
          .show();
    }
  }
  @TestTargets({
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "removeSessionCookie",
        args = {}),
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "removeExpiredCookie",
        args = {})
  })
  @SuppressWarnings("deprecation")
  public void testRemoveCookies() throws InterruptedException {
    // enable cookie
    mCookieManager.setAcceptCookie(true);
    assertTrue(mCookieManager.acceptCookie());
    assertFalse(mCookieManager.hasCookies());

    final String url = "http://www.example.com";
    final String cookie1 = "cookie1=peter";
    final String cookie2 = "cookie2=sue";
    final String cookie3 = "cookie3=marc";

    mCookieManager.setCookie(url, cookie1); // session cookie

    Date date = new Date();
    date.setTime(date.getTime() + 1000 * 600);
    String value2 = cookie2 + "; expires=" + date.toGMTString();
    mCookieManager.setCookie(url, value2); // expires in 10min

    long expiration = 3000;
    date = new Date();
    date.setTime(date.getTime() + expiration);
    String value3 = cookie3 + "; expires=" + date.toGMTString();
    mCookieManager.setCookie(url, value3); // expires in 3s

    String allCookies = mCookieManager.getCookie(url);
    assertTrue(allCookies.contains(cookie1));
    assertTrue(allCookies.contains(cookie2));
    assertTrue(allCookies.contains(cookie3));

    mCookieManager.removeSessionCookie();
    new DelayedCheck(TEST_DELAY) {
      protected boolean check() {
        String c = mCookieManager.getCookie(url);
        return !c.contains(cookie1) && c.contains(cookie2) && c.contains(cookie3);
      }
    }.run();

    Thread.sleep(expiration + 1000); // wait for cookie to expire
    mCookieManager.removeExpiredCookie();
    new DelayedCheck(TEST_DELAY) {
      protected boolean check() {
        String c = mCookieManager.getCookie(url);
        return !c.contains(cookie1) && c.contains(cookie2) && !c.contains(cookie3);
      }
    }.run();

    mCookieManager.removeAllCookie();
    new DelayedCheck(TEST_DELAY) {
      protected boolean check() {
        return mCookieManager.getCookie(url) == null;
      }
    }.run();
  }
 private void setCookie(String url, String cookiename, String cookieval) {
   CookieManager cookieManager = CookieManager.getInstance();
   cookieManager.setAcceptCookie(true);
   cookieManager.setCookie(url, cookiename + "=" + cookieval + ";Domain=.hktcs.com");
 }
 private static void addSidCookieForDomain(CookieManager cookieMgr, String domain, String sid) {
   String cookieStr = "sid=" + sid;
   cookieMgr.setCookie(domain, cookieStr);
 }