/** * @param cookiesHeader */ private static String updateWebkitResponseCookies(List<String> cookiesHeader, String requestUrl) { //write webkit cookie final CookieStore cookieStore = getCookieManager().getCookieStore(); if (cookieStore != null && cookiesHeader != null) { StringBuffer cookie = new StringBuffer(); for (String cookieHeader : cookiesHeader) { cookie.append(cookieHeader).append(";"); } android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance(); if (cookieManager != null && cookie.length() > 0) { String cookieStr = cookie.toString(); LogUtil.d(TAG, "write-webkit", cookieStr); cookieManager.setCookie(requestUrl, cookieStr); } } return null; }
/** * write net cookies * * @param cookiesHeader */ private static void updateNetResponseCookies(List<String> cookiesHeader) { //write net cookie final CookieStore cookieStore = getCookieManager().getCookieStore(); if (cookieStore != null && cookiesHeader != null) { HttpCookie cookieStr = null; for (String cookieHeader : cookiesHeader) { if (cookieHeader != null) { List<HttpCookie> cookies = HttpCookie.parse(cookieHeader); if (cookies != null && cookies.size() > 0) { cookieStr = cookies.get(0); LogUtil.d(TAG, "write-net", cookieStr); cookieStore.add(null, cookieStr); } } } } }
/** * Finds the ref tag cookie associated with a project. Returns `null` if no cookie has yet been set. */ protected static @Nullable HttpCookie findRefTagCookieForProject(final @NonNull Project project, final @NonNull CookieManager cookieManager, final @NonNull SharedPreferences sharedPreferences) { final String cookieName = cookieNameForProject(project); // First try finding the cookie in the cookie store final CookieStore cookieStore = cookieManager.getCookieStore(); for (final HttpCookie cookie : cookieStore.getCookies()) { if (cookieName.equals(cookie.getName())) { return cookie; } } // If we can't find it in the cookie store let's look in shared prefs final String cookieValue = sharedPreferences.getString(cookieName, null); if (cookieValue != null) { return buildCookieWithValueAndProject(cookieValue, project); } return null; }
public static void syncWebViewCookies(@NonNull Context context, @NonNull CookieStore cookieStore) { CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); cookieManager.removeSessionCookie(); cookieManager.removeAllCookie(); List<URI> urls = cookieStore.getURIs(); for (URI url : urls) { List<HttpCookie> cookies = cookieStore.get(url); for (HttpCookie cookie : cookies) { cookieManager.setCookie(url.toString(), cookie.toString()); } L.w("Cookies", cookieManager.getCookie(url.toString())); } CookieSyncManager.getInstance().sync(); }
/** * Clear the local stored authorization data */ public void clearAuthorizationData() { preferences.accessToken.clear(); preferences.idToken.clear(); preferences.userIdentity.clear(); if (BMSClient.getInstance() != null && BMSClient.getInstance().getCookieManager() != null) { CookieStore cookieStore = BMSClient.getInstance().getCookieManager().getCookieStore(); if(cookieStore != null) { for (URI uri : cookieStore.getURIs()) { for (HttpCookie cookie : cookieStore.get(uri)) { if (cookie.getName().equals(TAI_COOKIE_NAME)) { cookieStore.remove(uri, cookie); } } } } } }
private void resetCookie() { settings.edit().remove(prefKey).apply(); authCookie = ""; try { /* This step is *required* for PNA, and nicety for other services. PNA won't let you log in if you're still holding on to a valid authcookie, so we clear them out. */ URI loginURI = URI.create(url.getHost()); CookieStore cookies = ((CookieManager) CookieHandler.getDefault()).getCookieStore(); for (HttpCookie cookie : cookies.get(loginURI)) { cookies.remove(loginURI, cookie); } } catch (IllegalArgumentException e) { e.printStackTrace(); } cookieHasBeenSet = false; }
protected void setAuthCookieVal(String authCookie, String domain) { this.authCookie = authCookie; settings.edit().putString(prefKey, authCookie).apply(); /* this is technically unnecessary if OkHttp handled the authentication, because it will have already set the cookies in the CookieHandler. It doesn't seem to cause any issues just to re-add the cookies, though */ HttpCookie httpCookie = new HttpCookie(authCookieKey, authCookie); httpCookie.setDomain(domain); try { CookieStore cookies = ((CookieManager) CookieHandler.getDefault()).getCookieStore(); cookies.add(URI.create(domain), httpCookie); } catch (IllegalArgumentException e) { e.printStackTrace(); } cookieHasBeenSet = true; android.webkit.CookieManager.getInstance().setCookie(domain, httpCookie.getName() + "=" + httpCookie.getValue()); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) { android.webkit.CookieManager.getInstance().flush(); } else { CookieSyncManager.getInstance().sync(); } }
@Test public void shouldAddCookieToSharedPreferences() throws URISyntaxException { URI uri = URI.create("http://google.com"); CookieStore store = new CookieTray(preferences); HttpCookie httpCookie = new HttpCookie("name", "value"); store.add(uri, httpCookie); String cookieVal = new SerializableCookie(httpCookie).asString(); verify(editor).putString(uri.toString() + "|" + httpCookie.getName(), cookieVal); }
@Test public void shouldBeAbleToRemoveCookie() { addCookies(1, false); CookieStore store = new CookieTray(preferences); store.remove(URI.create("http://google.com/home0"), new HttpCookie("name0", "value0")); verify(editor).remove("http://google.com/home0|name0"); }
@Test public void shouldBeAbleToRemoveAllCookies() { doReturn(editor).when(editor).clear(); CookieStore store = new CookieTray(preferences); store.removeAll(); verify(editor).clear(); assertTrue("No cookies should be present after removing", store.getCookies().isEmpty()); }
/** * clear net cookies */ public static void clearNetCookies() { java.net.CookieManager cookieManager = getCookieManager(); CookieStore cookieStore = cookieManager.getCookieStore(); if (cookieStore != null) { cookieStore.removeAll(); } }
/** * net cookies */ private static String getNetRequestCookies() { final CookieStore cookieStore = getCookieManager().getCookieStore(); //net cookie if (cookieStore != null) { final List<HttpCookie> cookies = cookieStore.getCookies(); if (cookies != null && cookies.size() > 0) { //While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';' final String netCookie = TextUtils.join(";", cookies); LogUtil.d(TAG, "get-net", netCookie); return netCookie; } } return null; }
private void getUinAndPsessionid() throws InterruptedException, ExecutionException, TimeoutException, URISyntaxException { LOGGER.debug("开始获取uin和psessionid"); { CookieStore cookieStore = httpClient.getCookieStore(); cookieStore.add(new URI("qq.com"), new HttpCookie("pgv_info", "ssid=s" + RandomUtil.numberString(10))); cookieStore.add(new URI("qq.com"), new HttpCookie("pgv_pvid", RandomUtil.numberString(10))); httpClient .newRequest( "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=16&mibao_css=m_webqq&appid=501004106&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fw.qq.com%2Fproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20131024001") .method(HttpMethod.GET).agent(ApiURL.USER_AGENT).header("Referer", "http://w.qq.com/") .header("Upgrade-Insecure-Requests", "1").send(); } httpClient.newRequest("http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2").method(HttpMethod.GET) .agent(ApiURL.USER_AGENT).header("Referer", "http://w.qq.com/").header("Upgrade-Insecure-Requests", "1") .send(); JsonObject r = new JsonObject(); r.addProperty("ptwebqq", ptwebqq); r.addProperty("clientid", Client_ID); r.addProperty("psessionid", ""); r.addProperty("status", "online"); ContentResponse response = post(ApiURL.GET_UIN_AND_PSESSIONID, r); JsonObject result = getJsonObjectResult(response); this.psessionid = result.get("psessionid").getAsString(); this.uin = result.get("uin").getAsLong(); this.selfUserStatus = result.get("status").getAsString(); }
public static void writeTo( @NotNull CookieStore store, @NotNull OutputStream stream ) throws IOException { HashMap<URI, List<SerializableHttpCookie>> cookieMap = new HashMap<URI, List<SerializableHttpCookie>>(); List<URI> uris = store.getURIs(); for (URI uri : uris) { List<HttpCookie> cookies = store.get(uri); List<SerializableHttpCookie> serializableHttpCookies = new ArrayList<SerializableHttpCookie>(cookies.size()); for (HttpCookie cookie : cookies) { serializableHttpCookies.add(SerializableHttpCookie.of(cookie)); } cookieMap.put(uri, serializableHttpCookies); } ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(os); oos.writeObject(cookieMap); oos.flush(); stream.write(os.toByteArray()); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(oos); } }
@SuppressWarnings("unchecked") public static void readFrom( @NotNull CookieStore store, @NotNull InputStream stream ) throws IOException { HashMap<URI, List<SerializableHttpCookie>> cookieMap = null; ByteArrayInputStream is = new ByteArrayInputStream(IOUtils.toByteArray(stream)); ObjectInputStream ois = null; try { ois = new ObjectInputStream(is); Object object = ois.readObject(); if (object instanceof HashMap) { cookieMap = (HashMap<URI, List<SerializableHttpCookie>>) object; } } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(ois); } if (cookieMap == null) return; for (URI uri : cookieMap.keySet()) { List<SerializableHttpCookie> cookies = cookieMap.get(uri); for (SerializableHttpCookie cookie : cookies) { store.add(uri, cookie.toHttpCookie()); } } }
static void checkCookieNullUri() throws Exception { //get a cookie store implementation and add a cookie to the store with null URI CookieStore cookieStore = (new CookieManager()).getCookieStore(); //Check if removeAll() retrurns false on an empty CookieStore if (cookieStore.removeAll()) { fail = true; } checkFail("removeAll on empty store should return false"); HttpCookie cookie = new HttpCookie("MY_COOKIE", "MY_COOKIE_VALUE"); cookie.setDomain("foo.com"); cookieStore.add(null, cookie); //Retrieve added cookie URI uri = new URI("http://foo.com"); List<HttpCookie> addedCookieList = cookieStore.get(uri); //Verify CookieStore behaves well if (addedCookieList.size() != 1) { fail = true; } checkFail("Abnormal size of cookie jar"); for (HttpCookie chip : addedCookieList) { if (!chip.equals(cookie)) { fail = true; } } checkFail("Cookie not retrieved from Cookie Jar"); boolean ret = cookieStore.remove(null,cookie); if (!ret) { fail = true; } checkFail("Abnormal removal behaviour from Cookie Jar"); }
/** * Clears the cookies in the given cookie handler. Cookies can only be cleared if the * cookieHandler is a CookieManager with a non-null CookieStore. * * @param cookieHandler the cookie handler where cookies should be cleared * @return true if cookies were cleared; false otherwise */ public static boolean clearCookies(CookieHandler cookieHandler) { if (cookieHandler instanceof CookieManager) { CookieManager cookieManager = (CookieManager) cookieHandler; CookieStore cookieStore = cookieManager.getCookieStore(); if (cookieStore != null) { cookieStore.removeAll(); return true; } } return false; }
/** * Remove authorization by removing session cookie */ static void deauthorize() { if (cookieManager != null) { CookieStore store = cookieManager.getCookieStore(); store.removeAll(); } }
public boolean isLoggedIn() { final CookieStore cookieStore = HttpClientFactory.getInstance().getCookieStore(); boolean found = false; for (final HttpCookie cookie : cookieStore.getCookies()) { if ("pass_enabled".equals(cookie.getName()) && "1".equals(cookie.getValue())) { found = true; } } return found; }
@Test public void testStoredCookieRefTagForProject() { final CookieManager cookieManager = new CookieManager(); final CookieStore cookieStore = cookieManager.getCookieStore(); final Project project = ProjectFactory.project(); final RefTag refTag = RefTag.recommended(); // set the cookie and retrieve the ref tag cookieStore.add(null, new HttpCookie("ref_" + project.id(), refTag.tag() + "%3F" + SystemUtils.secondsSinceEpoch())); final RefTag retrievedRefTag = RefTagUtils.storedCookieRefTagForProject(project, cookieManager, sharedPreferences); assertNotNull(retrievedRefTag); assertEquals(refTag, retrievedRefTag); }
@Test public void testFindRefTagCookieForProject_WhenCookieExists() { final CookieManager cookieManager = new CookieManager(); final CookieStore cookieStore = cookieManager.getCookieStore(); final Project project = ProjectFactory.project(); final RefTag refTag = RefTag.recommended(); // set and retrieve the cookie cookieStore.add(null, new HttpCookie("ref_" + project.id(), refTag.tag() + "%3F" + SystemUtils.secondsSinceEpoch())); final HttpCookie cookie = RefTagUtils.findRefTagCookieForProject(project, cookieManager, sharedPreferences); assertNotNull(cookie); assertEquals(RefTagUtils.cookieNameForProject(project), cookie.getName()); assertEquals(RefTagUtils.cookieValueForRefTag(refTag), cookie.getValue()); }
public static CookieStore initInMemoryCookieStore() { CookieStore cookieStore = CookieStoreHolder.getCookieStore(); if (cookieStore == null) { CookieManager cm = new CookieManager(); cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieStoreHolder.setCookieStore(cm.getCookieStore()); } else { cookieStore.removeAll(); } return cookieStore; }
public WebkitCookieManager(Context context, CookieStore store, CookiePolicy cookiePolicy) { super(null, cookiePolicy); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { CookieSyncManager.createInstance(context); } webkitCookieManager = android.webkit.CookieManager.getInstance(); webkitCookieManager.setAcceptCookie(true); }
private boolean searchCookieStoreForValue(String value, CookieStore store) { for (HttpCookie c : store.getCookies()) { if (c.getValue().equals(value)) { return true; } } return false; }
private static void clearDownloaderCookies() { CookieHandler handler = CookieHandler.getDefault(); if (handler != null && handler instanceof CookieManager) { CookieStore cookies = ((CookieManager) handler).getCookieStore(); cookies.removeAll(); CookieHandler.setDefault(null); } }
public static synchronized boolean setup() { Settings settings = DataStoreManager.getSettings(); gmtOffset = settings.getGmtOffset(); sugarUrl = settings.getCrmUrl(); api = new SugarApi(sugarUrl); try { session = api.getSugarSession(new SugarCredentials(settings.getUser(), settings.getPassword())); String sessionId = session.getSessionID(); CookieManager manager = new CookieManager(); manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); CookieStore store = manager.getCookieStore(); store.add(new URI(sugarUrl), new HttpCookie("PHPSESSID", sessionId)); CookieHandler.setDefault(manager); return true; } catch (Exception e) { e.printStackTrace(); } return false; }
/** * Sets logged in user id from COOKIE_USER_ID if cookieStore has it */ private void initUserIdFromCookies() { CookieStore cookieStore = cookieManager.getCookieStore(); try { List<HttpCookie> cookies = cookieStore.get(new URI(EcoMapAPIContract.ECOMAP_SERVER_URL)); for (HttpCookie cookie : cookies) { if (cookie.getName().equals(EcoMapAPIContract.COOKIE_USER_ID)) { setUserId(cookie.getValue()); } } } catch (URISyntaxException e) { Log.e(LOG_TAG, e.getMessage(), e); } }
public void testCookieStoreRemoveAll() throws URISyntaxException { CookieStore cookieStore = new CookieManager().getCookieStore(); cookieStore.add(new URI("http://code.google.com/"), new HttpCookie("a", "android")); assertTrue(cookieStore.removeAll()); assertEquals(Collections.<URI>emptyList(), cookieStore.getURIs()); assertEquals(Collections.<HttpCookie>emptyList(), cookieStore.getCookies()); assertFalse("Expected removeAll() to return false when the call doesn't mutate the store", cookieStore.removeAll()); // RI6 fails this }
public void testCookieStoreAddAcceptsConflictingUri() throws URISyntaxException { CookieStore cookieStore = new CookieManager().getCookieStore(); HttpCookie cookieA = new HttpCookie("a", "android"); cookieA.setDomain(".android.com"); cookieA.setPath("/source/"); cookieStore.add(new URI("http://google.com/source/"), cookieA); assertEquals(Arrays.asList(cookieA), cookieStore.getCookies()); }
public void testCookieStoreRemoveRequiresUri() throws URISyntaxException { CookieStore cookieStore = new CookieManager().getCookieStore(); HttpCookie cookieA = new HttpCookie("a", "android"); cookieStore.add(new URI("http://android.com/source/"), cookieA); assertFalse("Expected remove() to take the cookie URI into account.", // RI6 fails this cookieStore.remove(new URI("http://code.google.com/"), cookieA)); assertEquals(Arrays.asList(cookieA), cookieStore.getCookies()); }
public Builder enableCookies(CookieStore cookieStore, CookiePolicy cookiePolicy) { if (cookiePolicy == null) { throw new NullPointerException("CookiePolicy may not be null"); } this.cookieHandler = new CookieManager(cookieStore, cookiePolicy); return this; }