private Answer<HttpResponse> createOkResponseWithCookie() { return new Answer<HttpResponse>() { @Override public HttpResponse answer(InvocationOnMock invocation) throws Throwable { HttpContext context = (HttpContext) invocation.getArguments()[1]; if (context.getAttribute(ClientContext.COOKIE_STORE) != null) { BasicCookieStore cookieStore = (BasicCookieStore) context.getAttribute(ClientContext.COOKIE_STORE); BasicClientCookie cookie = new BasicClientCookie("cookie", "meLikeCookie"); cookieStore.addCookie(cookie); } return OK_200_RESPONSE; } }; }
/** * Adds an {@link Cookie HTTP cookie}, replacing any existing equivalent cookies. * If the given cookie has already expired it will not be added, but existing * values will still be removed. * * @param cookie the {@link Cookie cookie} to be added * @see #addCookies(Cookie[]) */ @Override public synchronized void addCookie(final Cookie cookie) { if (cookie != null) { // first remove any old cookie that is equivalent cookies.remove(cookie); Date now = new Date(); if (!cookie.isExpired(now)) { Date targetExpiryDate = new Date(System.currentTimeMillis() + maxExpiresMillis); if (!cookie.isExpired(targetExpiryDate)) { try { if (cookie instanceof BasicClientCookie) { ((BasicClientCookie) cookie).setExpiryDate(targetExpiryDate); } else if (cookie instanceof BasicClientCookie2) { ((BasicClientCookie2) cookie).setExpiryDate(targetExpiryDate); } } catch (Exception e) { } } cookies.add(cookie); } } }
@Override protected void buildCookie(com.intuit.karate.http.Cookie c) { BasicClientCookie cookie = new BasicClientCookie(c.getName(), c.getValue()); for (Entry<String, String> entry : c.entrySet()) { switch (entry.getKey()) { case DOMAIN: cookie.setDomain(entry.getValue()); break; case PATH: cookie.setPath(entry.getValue()); break; } } if (cookie.getDomain() == null) { cookie.setDomain(uriBuilder.getHost()); } cookieStore.addCookie(cookie); }
public static CookieStore getuCookie() { CookieStore uCookie = new BasicCookieStore(); try { String COOKIE_S_LINKDATA = LemallPlatform.getInstance().getCookieLinkdata(); if (!TextUtils.isEmpty(COOKIE_S_LINKDATA)) { String[] cookies = COOKIE_S_LINKDATA.split("&"); for (String item : cookies) { String[] keyValue = item.split(SearchCriteria.EQ); if (keyValue.length == 2) { if (OtherUtil.isContainsChinese(keyValue[1])) { keyValue[1] = URLEncoder.encode(keyValue[1], "UTF-8"); } BasicClientCookie cookie = new BasicClientCookie(keyValue[0], keyValue[1]); cookie.setVersion(0); cookie.setDomain(".lemall.com"); cookie.setPath("/"); uCookie.addCookie(cookie); } } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return uCookie; }
private static void saveCookie(String url){ String cookie = CookieManager.getInstance().getCookie(url); if(cookie !=null && !cookie.equals("")){ String[] cookies = cookie.split(";"); for(int i=0; i< cookies.length; i++){ String[] nvp = cookies[i].split("="); BasicClientCookie c = new BasicClientCookie(nvp[0], nvp[1]); //c.setVersion(0); c.setDomain("kyfw.12306.cn"); MyCookieStore myCookieStore = null; if (MyApp.getInstance().getCommonBInfo().getHttpHelper().getHttpClient().getCookieStore() instanceof MyCookieStore){ myCookieStore = (MyCookieStore)MyApp.getInstance().getCommonBInfo().getHttpHelper().getHttpClient().getCookieStore(); } if (myCookieStore != null){ myCookieStore.addCookie(c); } } } CookieSyncManager.getInstance().sync(); }
public void SaveCookies(HttpResponse httpResponse) { Header[] headers = httpResponse.getHeaders("Set-Cookie"); String headerstr = headers.toString(); if (headers != null) { for (int i = 0; i < headers.length; i++) { String cookie = headers[i].getValue(); String[] cookievalues = cookie.split(";"); for (int j = 0; j < cookievalues.length; j++) { String[] keyPair = cookievalues[j].split("="); String key = keyPair[0].trim(); String value = keyPair.length > 1 ? keyPair[1].trim() : ""; BasicClientCookie newCookie = new BasicClientCookie(key, value); cookieStore.addCookie(newCookie); } } } }
private void loadCookies() throws IOException { CookieManager cm = getWebClient().getCookieManager(); File cookiesFile = Directories.META.getDir("cookies.json"); if (cookiesFile.exists()) { String content = HTMLUtil.readFile(cookiesFile); List<BasicClientCookie> list = new Gson().fromJson(content, new TypeToken<List<BasicClientCookie>>() { }.getType()); for (BasicClientCookie bc : list) { Cookie c = new Cookie(bc.getDomain(), bc.getName(), bc.getValue()); cm.addCookie(c); } } }
public void saveCookies() throws IOException { CookieManager cm = getWebClient().getCookieManager(); ArrayList<BasicClientCookie> list = new ArrayList<>(); for (Cookie c : cm.getCookies()) { BasicClientCookie bc = new BasicClientCookie(c.getName(), c.getValue()); bc.setDomain(c.getDomain()); bc.setPath(c.getPath()); list.add(bc); } File cookiesFile = Directories.META.getDir("cookies.json"); if (cookiesFile.exists()) { cookiesFile.delete(); } String o = new Gson().toJson(list); FileUtils.writeByteArrayToFile(cookiesFile, o.getBytes()); }
public static void setCookieStore(HttpResponse httpResponse) { System.out.println("----setCookieStore"); cookieStore = new BasicCookieStore(); // JSESSIONID String setCookie = httpResponse.getFirstHeader("Set-Cookie") .getValue(); String JSESSIONID = setCookie.substring("JSESSIONID=".length(), setCookie.indexOf(";")); System.out.println("JSESSIONID:" + JSESSIONID); // 新建一个Cookie BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", JSESSIONID); cookie.setVersion(0); //cookie.setDomain("127.0.0.1"); //cookie.setPath("/CwlProClient"); // cookie.setAttribute(ClientCookie.VERSION_ATTR, "0"); // cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "127.0.0.1"); // cookie.setAttribute(ClientCookie.PORT_ATTR, "8080"); // cookie.setAttribute(ClientCookie.PATH_ATTR, "/CwlProWeb"); cookieStore.addCookie(cookie); }
/** * Authentication with google account * @param cookies cookies list keys from google auth * @param login username associated to zds login * @param id user id on ZdS associated to login */ public void authToGoogle(List<HttpCookie> cookies, String login, String id) { if(login != null && id != null) { this.login = login; this.idUser = id; log.info("L'identifiant de l'utilisateur " + this.login + " est : " + idUser); cookieStore = new BasicCookieStore(); for(HttpCookie cookie:cookies) { BasicClientCookie c = new BasicClientCookie(cookie.getName(), cookie.getValue()); c.setDomain(cookie.getDomain()); c.setPath(cookie.getPath()); c.setSecure(cookie.getSecure()); c.setVersion(cookie.getVersion()); c.setComment(cookie.getComment()); cookieStore.addCookie(c); } context.setCookieStore(cookieStore); this.authenticated = true; } else { log.debug("Le login de l'utilisateur n'a pas pu être trouvé"); } }
/** * batchCookies * * @param cookiestring * the cookie string, eg.:"a=b;c=a" * @param domain * the domain * @param path * the path * @param expired * the expired date */ public synchronized void batchCookie(String cookiestring, String domain, String path, Date expired) { String[] ss = X.split(cookiestring, ";"); for (String s : ss) { StringFinder sf = StringFinder.create(s); String name = sf.nextTo("="); String value = sf.remain(); if (!X.isEmpty(name)) { removeCookie(name, domain, path); BasicClientCookie c = new BasicClientCookie(name, value); c.setDomain(domain); c.setPath(X.isEmpty(path) ? "/" : path); c.setExpiryDate(expired); cookies.addCookie(c); } } }
public void setCookies(Map<String, String> cookies, String domain, String path) { if (null == cookies || cookies.isEmpty()) { return; } for (String key : cookies.keySet()) { BasicClientCookie cookie = new BasicClientCookie(key, cookies.get(key)); if (domain.startsWith(HTTP_PRO)) { domain = domain.substring(HTTP_PRO.length()); } if (domain.startsWith(HTTPS_PRO)) { domain = domain.substring(HTTPS_PRO.length()); } cookie.setDomain(domain); if (StringUtils.isBlank(path)) { cookie.setPath("/"); } else { cookie.setPath(path); } cookieStore.addCookie(cookie); } }
@Test public void createCookieForHeaderElementTest() { String cookiePath = "/client/api"; String paramName = "paramName1"; String paramValue = "paramVale1"; NameValuePair[] parameters = new NameValuePair[1]; parameters[0] = new BasicNameValuePair(paramName, paramValue); String headerName = "headerElementName"; String headerValue = "headerElementValue"; HeaderElement headerElement = new BasicHeaderElement(headerName, headerValue, parameters); Mockito.doNothing().when(apacheCloudStackClient).configureDomainForCookie(Mockito.any(BasicClientCookie.class)); BasicClientCookie cookieForHeaderElement = apacheCloudStackClient.createCookieForHeaderElement(headerElement); Assert.assertNotNull(cookieForHeaderElement); Assert.assertEquals(headerName, cookieForHeaderElement.getName()); Assert.assertEquals(headerValue, cookieForHeaderElement.getValue()); Assert.assertEquals(paramValue, cookieForHeaderElement.getAttribute(paramName)); Assert.assertEquals(cookiePath, cookieForHeaderElement.getPath()); Mockito.verify(apacheCloudStackClient).configureDomainForCookie(Mockito.eq(cookieForHeaderElement)); }
/** * Create an HttpClient cookie from a JMeter cookie */ private org.apache.http.cookie.Cookie makeCookie(Cookie jmc) { long exp = jmc.getExpiresMillis(); BasicClientCookie ret = new BasicClientCookie(jmc.getName(), jmc.getValue()); ret.setDomain(jmc.getDomain()); ret.setPath(jmc.getPath()); ret.setExpiryDate(exp > 0 ? new Date(exp) : null); // use null for no expiry ret.setSecure(jmc.getSecure()); ret.setVersion(jmc.getVersion()); if(jmc.isDomainSpecified()) { ret.setAttribute(ClientCookie.DOMAIN_ATTR, jmc.getDomain()); } if(jmc.isPathSpecified()) { ret.setAttribute(ClientCookie.PATH_ATTR, jmc.getPath()); } return ret; }
@Override public BasicHttpContext createContext(final HttpHost targetHost) { final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie clientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue()); clientCookie.setDomain(targetHost.getHostName()); clientCookie.setPath("/"); cookieStore.addCookie(clientCookie); final BasicHttpContext context = new BasicHttpContext(); context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); return context; }
private void readCookiesFromFile() { String json; try { json = Files.toString(cookiesFile, Charset.defaultCharset()); } catch (IOException e) { throw new WallhavenException("Could not load cookies from file", e); } if (json.isEmpty()) return; TypeToken<Set<BasicClientCookie>> typeToken = new TypeToken<Set<BasicClientCookie>>() { }; Set<Cookie> cookiesInFile = jsonSerializer.fromJson(json, typeToken.getType()); for (Cookie cookie : cookiesInFile) { store.addCookie(cookie); } }
@Test public void testSerialization() throws Exception { final BasicCookieStore orig = new BasicCookieStore(); orig.addCookie(new BasicClientCookie("name1", "value1")); orig.addCookie(new BasicClientCookie("name2", "value2")); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); final ObjectOutputStream outstream = new ObjectOutputStream(outbuffer); outstream.writeObject(orig); outstream.close(); final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inbuffer = new ByteArrayInputStream(raw); final ObjectInputStream instream = new ObjectInputStream(inbuffer); final BasicCookieStore clone = (BasicCookieStore) instream.readObject(); final List<Cookie> expected = orig.getCookies(); final List<Cookie> clones = clone.getCookies(); Assert.assertNotNull(expected); Assert.assertNotNull(clones); Assert.assertEquals(expected.size(), clones.size()); for (int i = 0; i < expected.size(); i++) { Assert.assertEquals(expected.get(i).getName(), clones.get(i).getName()); Assert.assertEquals(expected.get(i).getValue(), clones.get(i).getValue()); } }
@Test public void testCookieIdentityComparasionByNameDomainAndPath() { final CookieIdentityComparator comparator = new CookieIdentityComparator(); final BasicClientCookie c1 = new BasicClientCookie("name", "value1"); c1.setDomain("www.domain.com"); c1.setPath("/whatever"); final BasicClientCookie c2 = new BasicClientCookie("name", "value2"); c2.setDomain("www.domain.com"); c2.setPath("/whatever"); Assert.assertTrue(comparator.compare(c1, c2) == 0); final BasicClientCookie c3 = new BasicClientCookie("name", "value1"); c3.setDomain("www.domain.com"); c3.setPath("/whatever"); final BasicClientCookie c4 = new BasicClientCookie("name", "value2"); c4.setDomain("domain.com"); c4.setPath("/whatever-not"); Assert.assertFalse(comparator.compare(c3, c4) == 0); }
@Test public void testCookieIdentityComparasionByNameDomainAndNullPath() { final CookieIdentityComparator comparator = new CookieIdentityComparator(); final BasicClientCookie c1 = new BasicClientCookie("name", "value1"); c1.setDomain("www.domain.com"); c1.setPath("/"); final BasicClientCookie c2 = new BasicClientCookie("name", "value2"); c2.setDomain("www.domain.com"); c2.setPath(null); Assert.assertTrue(comparator.compare(c1, c2) == 0); final BasicClientCookie c3 = new BasicClientCookie("name", "value1"); c3.setDomain("www.domain.com"); c3.setPath("/whatever"); final BasicClientCookie c4 = new BasicClientCookie("name", "value2"); c4.setDomain("domain.com"); c4.setPath(null); Assert.assertFalse(comparator.compare(c3, c4) == 0); }
protected synchronized void clearCookieForHost(String sessionHost) throws Exception { Cookie sessionCookie = null; for (Cookie cookie : cookieStore.getCookies()) { String cookieDomain = cookie.getDomain(); if (cookieDomain != null) { if (sessionHost.equals(cookieDomain) || sessionHost.indexOf(cookieDomain) != -1 || cookieDomain.indexOf(sessionHost) != -1) { sessionCookie = cookie; break; } } } if (sessionCookie != null) { BasicClientCookie httpCookie = new BasicClientCookie(sessionCookie.getName(), sessionCookie.getValue()); httpCookie.setExpiryDate(new Date(0)); httpCookie.setVersion(1); httpCookie.setPath(sessionCookie.getPath()); httpCookie.setDomain(sessionCookie.getDomain()); cookieStore.addCookie(httpCookie); } cookieStore.clearExpired(new Date()); // this should clear the cookie }
private String storeCookie(CloseableHttpResponse response) { Header cookieHeader = response.getFirstHeader("set-cookie"); if (cookieHeader != null) { mTokenHeader = cookieHeader.getValue(); String token = mTokenHeader.substring(8, mTokenHeader.indexOf(';')); mCookieStore.clear(); BasicClientCookie cookie = new BasicClientCookie(BBOX_COOKIE_NAME, token); cookie.setDomain(BBOX_HOST); mCookieStore.addCookie(cookie); return token; } return null; }
public static ArrayList<BasicClientCookie> getCookiesFromHeaders(ArrayList<String> headers){ ArrayList<String> values = getHeaderValues("Cookie", headers); if(values != null && values.size() > 0){ ArrayList<BasicClientCookie> cookies = new ArrayList<BasicClientCookie>(); for(String value : values){ ArrayList<BasicClientCookie> lineCookies = parseRawCookie(value); if(lineCookies != null && lineCookies.size() > 0){ cookies.addAll(lineCookies); } } // remove google and cloudflare cookies Iterator<BasicClientCookie> it = cookies.iterator(); while(it.hasNext()){ BasicClientCookie cookie = (BasicClientCookie) it.next(); if(cookie.getName().startsWith("__utm") || cookie.getName().equals("__cfduid")) it.remove(); } return cookies.size() > 0 ? cookies : null; } return null; }
@Override protected Boolean doInBackground(Session... sessions) { Session session = sessions[0]; BasicClientCookie user = session.mCookies.get("c_user"); if (user != null) { String fbUserId = user.getValue(), fbGraphUrl = "https://graph.facebook.com/" + fbUserId + "/", fbPictureUrl = fbGraphUrl + "picture"; session.mUserName = getUserName(fbGraphUrl); session.mPicture = getUserImage(fbPictureUrl); } return true; }
@Test public void testCookiesAreCapturedWhenRequested() throws IOException { proxy.setCaptureContent(true); proxy.newHar("Test"); BasicClientCookie cookie = new BasicClientCookie("foo", "bar"); cookie.setDomain("127.0.0.1"); cookie.setPath("/"); client.getCookieStore().addCookie(cookie); // set the cookie on the server side String body = IOUtils.readFully(client.execute(new HttpGet(ECHO_URL)).getEntity().getContent()); System.out.println(body); Har har = proxy.getHar(); HarEntry entry = har.getLog().getEntries().get(0); HarCookie harCookie = entry.getRequest().getCookies().get(0); Assert.assertEquals("foo", harCookie.getName()); Assert.assertEquals("bar", harCookie.getValue()); }
public static ConcurrentCookieJar createApacheCookieStore(HttpDownloaderConfig config) { List<HttpDownloaderConfig.Cookie> cookies = config.getCookies(); if (cookies == null) { return null; } ConcurrentCookieJar store = new ConcurrentCookieJar(); for (HttpDownloaderConfig.Cookie cookie : cookies) { String[] values = cookie.cookie.split("; "); for (int i = 0; i < values.length; i++) { String[] kv = values[i].split("=", 2); BasicClientCookie cc = new BasicClientCookie(kv[0], kv[1]); cc.setPath(cookie.path); cc.setDomain(cookie.domain); store.addCookie(cc); } } return store; }
public HttpContext prepareContext(Job job) { CookieStore store = new BasicCookieStore(); if (cookies() != null) cookies().forEach(cookie -> { BasicClientCookie theCookie = new BasicClientCookie(cookie.name(), cookie.value()); theCookie.setDomain(cookie.domain()); theCookie.setPath(cookie.path()); theCookie.setExpiryDate(new Date(cookie.expires())); theCookie.setSecure(cookie.secure()); store.addCookie(theCookie); }); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, store); return localContext; }
private BasicClientCookie generateCookie(String cookie) { Map<String, String> cookieMap = generateCookieMap(cookie); BasicClientCookie clientCookie = new BasicClientCookie(cookieMap.get("name"), cookieMap.get("value")); if (cookieMap.containsKey("domain")) { clientCookie.setDomain(cookieMap.get("domain")); } if (cookieMap.containsKey("path")) { clientCookie.setPath(cookieMap.get("path")); } if (cookieMap.containsKey("version")) { clientCookie.setVersion(Integer.parseInt(cookieMap.get("version"))); } /* TODO if (cookieMap.containsKey("expiry")) { clientCookie.setExpiryDate(cookieMap.get("expiry")); } */ return clientCookie; }
/** * Share the cookies with HttpClientTask */ public void shareCookies(){ Object store = getCookieStore(); if (store == null){ store = new BasicCookieStore(); this.getParametersInner().put(HttpClientTask.PARAM_HTTP_COOKIES, store); } CookieStore cookieStore = (CookieStore)store; for (Cookie cookie : this.getDriver().manage().getCookies()){ BasicClientCookie newCookie = new BasicClientCookie(cookie.getName(), cookie.getValue()); newCookie.setDomain(cookie.getDomain()); newCookie.setPath(cookie.getPath()); newCookie.setExpiryDate(cookie.getExpiry()); newCookie.setSecure(cookie.isSecure()); cookieStore.addCookie(newCookie); } }
@Override public DefaultHttpClient create(final HttpMethod method, final URI uri) { final CookieStore cookieStore = new BasicCookieStore(); // Populate cookies if needed final BasicClientCookie cookie = new BasicClientCookie("name", "value"); cookie.setVersion(0); cookie.setDomain(".mycompany.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); final DefaultHttpClient httpClient = super.create(method, uri); httpClient.setCookieStore(cookieStore); return httpClient; }
public void onCreate() { super.onCreate(); httpClient = new DefaultHttpClient(); sharedpreferences = getSharedPreferences("MeNextPreferences", Context.MODE_PRIVATE); String menext_domain = this.getString(R.string.menext_url); List<String> cookies = new ArrayList<String>(); cookies.add("PHPSESSID"); cookies.add("seriesId"); cookies.add("token"); for (int i = 0; i < cookies.size(); i++) { String cookie_name = cookies.get(i); String cookie_value = sharedpreferences.getString(cookie_name, ""); Cookie cookie = new BasicClientCookie(cookie_name, cookie_value); ((BasicClientCookie) cookie).setDomain(menext_domain); httpClient.getCookieStore().addCookie(cookie); } }
public static String getAccessToken(String sessionId, String csrfToken) throws Exception { DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setBooleanParameter( "http.protocol.handle-redirects", false); CookieStore cookies = new BasicCookieStore(); BasicClientCookie csrfCookie = new BasicClientCookie( "csrftoken", csrfToken); csrfCookie.setDomain(Urls.OAUTH_HOSTNAME); csrfCookie.setPath("/"); cookies.addCookie(csrfCookie); BasicClientCookie sessionCookie = new BasicClientCookie( "sessionid", sessionId); sessionCookie.setDomain(Urls.OAUTH_HOSTNAME); sessionCookie.setPath("/"); cookies.addCookie(sessionCookie); client.setCookieStore(cookies); authorizeClient(client); return getAccessToken(client, getAuthorizationCode(client, authorizeClient(client, csrfToken))); }
/** * Converts Selenium cookie to Apache http client. * @param browserCookie selenium cookie. * @return http client format. */ protected ClientCookie convertCookie(Cookie browserCookie) { BasicClientCookie cookie = new BasicClientCookie(browserCookie.getName(), browserCookie.getValue()); String domain = browserCookie.getDomain(); if (domain != null && domain.startsWith(".")) { // http client does not like domains starting with '.', it always removes it when it receives them domain = domain.substring(1); } cookie.setDomain(domain); cookie.setPath(browserCookie.getPath()); cookie.setExpiryDate(browserCookie.getExpiry()); cookie.setSecure(browserCookie.isSecure()); if (browserCookie.isHttpOnly()) { cookie.setAttribute("httponly", ""); } return cookie; }
public static void getUseCookie(Context context, String url, HashMap hashMap, AsyncHttpResponseHandler responseHandler) { PersistentCookieStore myCookieStore = new PersistentCookieStore(context); if (BasicUtils.judgeNotNull(hashMap)) { Iterator iterator = hashMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); Object key = entry.getKey(); Object value = entry.getValue(); Cookie cookie = new BasicClientCookie(key.toString(), value.toString()); myCookieStore.addCookie(cookie); } } AsyncHttpClient client = new AsyncHttpClient(); client.setCookieStore(myCookieStore); client.get(getAbsoluteUrl(url), responseHandler); }
public static void postUseCookie(Context context, String url, HashMap hashMap, AsyncHttpResponseHandler responseHandler) { PersistentCookieStore myCookieStore = new PersistentCookieStore(context); if (BasicUtils.judgeNotNull(hashMap)) { Iterator iterator = hashMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); Object key = entry.getKey(); Object value = entry.getValue(); Cookie cookie = new BasicClientCookie(key.toString(), value.toString()); myCookieStore.addCookie(cookie); } } AsyncHttpClient client = new AsyncHttpClient(); client.setCookieStore(myCookieStore); client.post(getAbsoluteUrl(url), responseHandler); }