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));
  }
Esempio n. 2
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));
  }
Esempio n. 3
0
  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;
  }
 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"));
 }
 /**
  * Gets all cookies for a given domain name
  *
  * @param domain Domain name to fetch cookies for
  * @return Set of cookie objects for given domain
  */
 public List<Cookie> getCookies(String domain) {
   cookieManager.removeExpiredCookie();
   String cookies = cookieManager.getCookie(domain);
   List<Cookie> result = new LinkedList<Cookie>();
   if (cookies == null) {
     return result;
   }
   for (String cookie : cookies.split(COOKIE_SEPARATOR)) {
     String[] cookieValues = cookie.split("=");
     if (cookieValues.length >= 2) {
       result.add(new Cookie(cookieValues[0].trim(), cookieValues[1], domain, null, null));
     }
   }
   return result;
 }
  @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();
  }
  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();
  }
  @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();
  }
  @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();
  }
Esempio n. 10
0
  private void test() {

    HttpURLConnection fbc;
    String response = "";

    boolean isConnectionError = false;
    String connectionErrorMessage = "";
    String uidstr = Long.toString(uid);
    boolean unknown = true;
    long random = new Random().nextInt();
    long channel = 65;
    long seq = 0;

    String endpoint = createEndpoint(channel, random, unknown, uidstr, seq);
    String endpointHost = createEndpointHost(channel, random, unknown, uidstr, seq);
    String endpointFile = createEndpointFile(channel, random, unknown, uidstr, seq);

    // endpoint = "http://www.google.com";
    int mConnectionTimeout = 50000;
    String REQUEST_METHOD = "GET";

    response = "";

    CookieManager cm = CookieManager.getInstance();
    String cookies = cm.getCookie("facebook.com");

    Log.d(LOG_TAG, "cookie: " + cookies);
    try {
      HttpClientConnection httpClientConn;

      URL url = new URL("http", endpointHost, 80, endpointFile);
      Log.d(LOG_TAG, "url to connect:" + url.toString());
      fbc = (HttpURLConnection) url.openConnection();
      fbc.setUseCaches(true);
      fbc.setConnectTimeout(mConnectionTimeout);
      fbc.setRequestMethod(REQUEST_METHOD);
      fbc.setRequestProperty("Content-type", REQUEST_CONTENT_TYPE);
      fbc.setRequestProperty("User-Agent", REQUEST_USER_AGENT);
      fbc.setRequestProperty("Accept-Language", REQUEST_ACCEPT_LANGUAGE);
      fbc.setRequestProperty("Accept", REQUEST_ACCEPT);
      fbc.setRequestProperty("Accept-Charset", REQUEST_ACCEPT_CHARSET);
      fbc.setRequestProperty("Cookie", cookies);

      // DataOutputStream dos = new DataOutputStream(fbc.getOutputStream());
      // dos.writeBytes(response);
      // dos.flush();
      // dos.close();

      // fbc.connect();
      // fbc.getContent();

      /*
      try{
      	Object obj = fbc.getContent();
      	Log.d(LOG_TAG,"content class: " + obj.getClass().getCanonicalName());
      }

      catch(Exception e){

      }
      */

      // String responseMsg = fbc.getResponseMessage();
      // Log.d(LOG_TAG,"response message:"+responseMsg);
      InputStream is = fbc.getInputStream();
      BufferedReader breader =
          new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      int linecount = 0;

      while (true) {
        String line = breader.readLine();
        if (line == null) {
          break;
        }
        linecount++;
        response += line;
        Log.d(LOG_TAG, linecount + ":" + line);
      }

      Log.d(LOG_TAG, "TEST_DONE");

    } catch (MalformedURLException e) {
      e.printStackTrace();
      isConnectionError = true;
      connectionErrorMessage = "MalformedURLException: " + e.getMessage();
    } catch (ProtocolException e) {
      e.printStackTrace();
      isConnectionError = true;
      connectionErrorMessage = "ProtocolException: " + e.getMessage();
    } catch (UnknownHostException e) {
      e.printStackTrace();
      isConnectionError = true;
      connectionErrorMessage = "UnknownHostException: " + e.getMessage();
    } catch (IOException e) {
      e.printStackTrace();
      isConnectionError = true;
      connectionErrorMessage = "IOException: " + e.getMessage();
    }
  }
Esempio n. 11
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();
    }
  }